-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexpressionSolving.cpp
122 lines (111 loc) · 3 KB
/
expressionSolving.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
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
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
vector<string> Tokenize(string & expression, unordered_map<string, int> & opMap)
{
vector<string> tokens = {};
string temp = "";
for(char c : expression)
{
if( c == ' ') continue;
else if( opMap.find(string(1, c)) != opMap.end())
{
if(temp != "")
tokens.push_back(temp);
temp = "";
tokens.push_back(string(1, c));
}
else temp += c;
}
if(temp != "")
tokens.push_back(temp);
return tokens;
}
vector<string> InfixToPostfix(vector<string> & infix, unordered_map <string, int> & opMap)
{
vector<string> postfix = {};
vector<string> stack = { "("};
infix.push_back(")");
for(string token : infix)
{
//cout << token << endl;
if(opMap.find(token) == opMap.end()) // oparand
postfix.push_back(token);
else if( token == "(")
stack.push_back(token);
else if (token == ")")
{
while(stack.back() != "(")
{
postfix.push_back(stack.back());
stack.pop_back();
}
stack.pop_back();
}
else // operator
{
while(stack.size() > 0 && opMap[token] <= opMap[stack.back()])
{
postfix.push_back(stack.back());
stack.pop_back();
}
stack.push_back(token);
}
}
return postfix;
}
float CalculatePostfix(vector<string> & postfix, unordered_map<string, int> &opMap)
{
vector<float> evaluationStack = {};
for(string token : postfix)
{
if(opMap.find(token) != opMap.end())
{
float n1 = evaluationStack[evaluationStack.size() - 1];
float n2 = evaluationStack[evaluationStack.size() - 2];
switch(token[0])
{
case '+':
n2 = n2 + n1;
break;
case '-':
n2 = n2 - n1;
break;
case '*':
n2 = n2 * n1;
break;
case '/':
n2 = n2 / n1;
break;
}
evaluationStack.pop_back();
evaluationStack.pop_back();
evaluationStack.push_back(n2);
}
else
{
evaluationStack.push_back(atof(token.c_str()));
}
}
return evaluationStack[0];
}
int main()
{
unordered_map<string, int> opMap = {
{ "*", 2},
{ "/", 2},
{ "+", 1},
{ "-", 1},
{ "(", -1},
{ ")", -1},
};
string expression;
getline(cin, expression);
vector<string> tokens = Tokenize(expression, opMap); //infix : a * b
tokens = InfixToPostfix(tokens, opMap); // postfix : a b *
float result = CalculatePostfix(tokens, opMap);
cout << result << endl;
}