blob: 76c91509c036149e81b48e16fd9d11658a27eb9f (
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
|
#include "CellFormula.h"
#include "CellDouble.h"
#include <cstring>
#include <iostream>
double pow(double x, unsigned 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) {
double lval = formula[index].left->getNumeralValue();
while (formula[index].right < 0) {
switch (-formula[index++].right) {
case '+' : lval += formula[index].left->getNumeralValue(); break;
case '-' : lval -= formula[index].left->getNumeralValue(); break;
case '*' : lval *= formula[index].left->getNumeralValue(); break;
case '/' : lval /= formula[index].left->getNumeralValue(); break;
case '^' : lval = pow(lval, formula[index].left->getNumeralValue()); break;
}
}
switch(formula[index].right) {
case '+' : return lval + calculate(++index);
case '-' : return lval - calculate(++index);
case '*' : return lval * calculate(++index);
case '/' : return lval / calculate(++index);
case '^' : return pow(lval, calculate(++index));
case '\0' :
default : return lval;
}
}
CellFormula::CellFormula(const char* str, const List<List<Cell*>>* tableCells) : localCells(), formula(), rawFormula() {
this->tableCells = tableCells;
CellFormula::parseAndSetValue(str);
}
#include <iostream>
double CellFormula::getNumeralValue() {
return calculate();
}
String CellFormula::getValueForPrint() {
for (unsigned i = 0; i < formula.get_count(); i++)
std::cout << "[" << formula[i].left->getNumeralValue() << " " << ((formula[i].right < 0) ? (int)formula[i].right : (char)formula[i].right) << std::endl;
return String() += calculate();
}
void CellFormula::parseAndSetValue(const char* str) {
rawFormula = String(str);
Cell* cellToAdd;
char currOp;
while (*str != '\0') {
str++;
while (*str == ' ') str++;
if (*str == 'R') {
unsigned row = atoi(++str);
while (*str != 'C') str++;
unsigned col = atoi(++str);
while (*str != ' ' && *str != '\0') str++;
while (*str == ' ') str++;
cellToAdd = (*tableCells)[row][col];
currOp = *str;
}
else {
double val = atof(str);
while ((*str >= '0' && *str <= '9') || *str == ' ') str++;
localCells.add(CellDouble(val));
cellToAdd = &localCells[localCells.get_count() - 1];
currOp = *str;
}
if (currOp == '^') currOp *= -1;
else if ((currOp == '+' || currOp == '-') && formula.get_count() != 0) {
Pair<Cell*, char>& prev = formula[formula.get_count() - 1];
if (prev.right == '*' || prev.right == '/' || prev.right == '-') prev.right *= -1;
}
formula.add({cellToAdd, currOp});
}
}
void CellFormula::readFromFile(std::ifstream& file) {
file >> rawFormula;
}
void CellFormula::writeToFile(std::ofstream& file) {
file << rawFormula;
}
|