-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShuntingYard.cpp
96 lines (83 loc) · 2.53 KB
/
ShuntingYard.cpp
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
#include "ShuntingYard.h"
double ShuntingYard::getNotation(string &line) {
stack<double> test;
stack<string> array;
string current;
for (int i = 0; i < line.length(); ++i) {
check::ifUnary(i, line);
current = line[i];
if (check::isNumber(current)) {
current = getNumber(i, line);
double elem = calc::toDouble(current);
test.addElement(elem);
} else if (check::isOpen(current)) {
array.addElement(current);
} else if (check::isClose(current)) {
pushScope(array, test);
} else {
pushOperation(array, current, test);
}
}
takeCashBack(array, test);
double result = test.getElement();
return result;
}
void ShuntingYard::pushOperation(stack<string> &array, string ¤t, stack<double> &test) {
if (!array.isEmpty()) {
while (!array.isEmpty()) {
string temp = array.getElement();
if (check::getPrecedence(current) <= check::getPrecedence(temp) && !check::getAssociativity(current) ||
check::getPrecedence(current) < check::getPrecedence(temp) && check::getAssociativity(current)) {
addOperation(test, temp);
array.deleteElement();
}
else{
break;
}
}
}
array.addElement(current);
}
void ShuntingYard::takeCashBack(stack<string> &array, stack<double> &test) {
while (!array.isEmpty()) {
string current = array.getElement();
addOperation(test, current);
array.deleteElement();
}
}
void ShuntingYard::pushScope(stack<string> &array, stack<double> &test) {
while (!array.isEmpty()) {
string current = array.getElement();
if (current == "(") {
array.deleteElement();
break;
} else {
addOperation(test, current);
array.deleteElement();
}
}
}
string ShuntingYard::getNumber(int &start, string &line) {
string number;
while (start < line.length()) {
if (check::isNumber(line[start]) || line[start] == '.')
number += line[start++];
else
break;
}
start--;
return number;
}
void ShuntingYard::addOperation(stack<double> &test, string &oper) {
double a, b;
a = test.getElement();
test.deleteElement();
if (oper == "m") {
b = 0;
} else {
b = test.getElement();
test.deleteElement();
}
double res = calc::operation(a, b, oper);
test.addElement(res);
}