Website Summary Files Commits Branches @commit @diff @stats
path: root / src / Models / CellFormula.cpp
blob: fead01de739c2d8e58463920c5912e8f98a414bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#include "CellFormula.h"
#include "CellDouble.h"
#include <cstring>
#include <iostream>
#include <stdexcept>

const Cell* CellFormula::ptrByInd(Pair<int, int> loc) const {
	if (loc.left < 0) {
		if (loc.right < 0 || localCells.get_count() - 1 < loc.right) return nullptr;
		return &localCells[loc.right];
	}
	
	if (loc.right < 0
		|| (*tableCells).get_count() - 1 < loc.left || (*tableCells)[loc.left].get_count() - 1 < loc.right)
		return nullptr;
	return (*tableCells)[loc.left][loc.right];
}

double pow(double x, int y) {
	if (y <= 0) return 1;

	double res = x;
	for (unsigned i = 1; i < y; i++)
		res *= x;
	return res;
}

double CellFormula::calculate(unsigned index) const {
	const Cell* currCell = ptrByInd(formula[index].left);
	double numVal = (currCell == nullptr) ? 0 : currCell->getNumeralValue();

	while (formula[index].right < 0) {
		switch (-formula[index++].right) {
			case '+' : numVal += ptrByInd(formula[index].left)->getNumeralValue(); break;
			case '*' : numVal *= ptrByInd(formula[index].left)->getNumeralValue(); break;
			case '/' : if (ptrByInd(formula[index].left)->getNumeralValue() == 0) throw std::logic_error("Error: Divion by zero!");
					   numVal /= ptrByInd(formula[index].left)->getNumeralValue(); break;
			case '^' : numVal  = pow(numVal, ptrByInd(formula[index].left)->getNumeralValue()); break;
		}
	}

	double temp;
	switch(formula[index].right) {
		case '+'  : return numVal + calculate(++index);
		case '*'  : return numVal * calculate(++index);
		case '/'  : temp = calculate(++index);
					if (temp == 0) throw std::logic_error("Error: Division by zero!");
					return numVal / temp;
		case '^'  : return pow(numVal, calculate(++index));
		case '\0' :
		default   : return numVal;
	}
}

CellFormula::CellFormula(const char* str, const List<List<Cell*>>* tableCells) : localCells(), formula(), rawFormula() {
	this->tableCells = tableCells;
	CellFormula::parseAndSetValue(str);
}

#include <iostream>

double CellFormula::getNumeralValue() const {
	try {
		return calculate();
	}
	catch (std::logic_error e) {
		return 0;
	}
}

String CellFormula::getValueForPrint() const {
	try {
		return String() += calculate();
	}
	catch (std::logic_error e) {
		return "Error";
	}
}

// Rough implementation of the grammar
//
// S -> WDWOS | WD.DWOS | WRDCDWOS | W
// O -> + | - | * | / | ^
// D -> D0 | D1 | ... | D9 | 0 | 1 | ... | 9
// W -> W | epsilon
//
// over the string

void W(const char*& str) {
	while (*str == ' ') str++;
}

void D(const char*& str, List<char>& buffer) {
	while (*str >= '0' && *str <= '9')
		buffer.add(*(str++));
}

void O(const char*& str, char& buffer) {
	if (*str == '+' || *str == '-' || *str == '*' || *str == '/' || *str == '^' || *str == '\0')
		buffer = *(str++);
	else buffer = -2;
}

/*!
 * Each math operation is represented with a Pair that holds indecies of cell reference
 * and a character for the operation.
 *
 * Negatve value for the operation character means it's with priority and the result get's calculated
 * immediately (rather than recursively, taking into account other values).
 *
 * \exception std::logic_error("Error: Invalid column character!") Thrown when there is something between Rx and C in cell references
 * \exception std::logic_error("Error: Invalid value!") Thrown when met value isn't a cell reference or number
 * \exception throw std::logic_error("Error: Could not find operand!") Thrown when there isn't an operator character between two values
 */
void CellFormula::parseAndSetValue(const char* str) {
	rawFormula = String(str);

	formula.clear();
	localCells.clear();
	Pair<int, int> loc;
	char currOp = -2;

	str++; // Removes = from the beginning
	while (*str != '\0') {
		List<char> buffer;
		W(str);
		if (*str == 'R') {
			D(++str, buffer);
			loc.left = atoi(buffer.raw_data()) - 1;
			if (*str != 'C') throw std::logic_error("Error: Invalid column character!");
			str++;
			buffer.clear();
			D(str, buffer);
			loc.right = atoi(buffer.raw_data()) - 1;
		}
		else if (*str >= '0' && *str <= '9') {
			D(str, buffer);
			if (*str == '.') {
				buffer.add(*str);
				D(++str, buffer);
				localCells.add(CellDouble(atof(buffer.raw_data())));
			}
			else
				localCells.add(CellDouble(atoi(buffer.raw_data())));

			loc.left = -1;
			loc.right = (int)(localCells.get_count() - 1);
		}
		else
			throw std::logic_error("Error: Invalid value!");

		W(str);
		O(str, currOp);
		if (currOp == -2) throw std::logic_error("Error: Could not find operand!");

		// Operator priority magic
		if (currOp == '^') currOp *= -1;
		else if ((currOp == '+' || currOp == '-') && formula.get_count() != 0) {
			for (unsigned i = formula.get_count() - 1; i < formula.get_count() && (formula[i].right == '*' || formula[i].right == '/'); i--)
				if (formula[i].right > 0) formula[i].right *= -1;
		}

		if (currOp == '-') { // a - b turns into a + -1 * b
			formula.add({loc, '+'});
			localCells.add(CellDouble(-1.0));
			loc.left = -1;
			loc.right = (int)(localCells.get_count() - 1);
			currOp = '*' * -1;
		}

		formula.add(Pair<Pair<int, int>, char>(loc, currOp));
	}
}

void CellFormula::writeToFile(std::ofstream& file) {
	file << '"' << rawFormula << '"';
}