Skip to content

Commit d425709

Browse files
committed
Add parsing of simple arithmetic expressions (shunting yard algorithm)
1 parent f594f45 commit d425709

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <iostream>
2+
#include <map>
3+
#include <string>
4+
#include <stack>
5+
#include <queue>
6+
#include <sstream>
7+
#include <cassert>
8+
9+
using namespace std;
10+
11+
// precedences
12+
map<char, int> prec{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
13+
14+
// handles +, -, *, / and parentheses
15+
// only handles single digit, positive numbers for simplicity
16+
int shuntyard(stringstream& ss) {
17+
char c;
18+
queue<char> output;
19+
stack<char> ops;
20+
while (ss >> c) {
21+
if (isdigit(c)) {
22+
output.push(c);
23+
} else if (c == '(') {
24+
ops.push(c);
25+
} else if (c == ')') {
26+
while (ops.top() != '(') {
27+
output.push(ops.top());
28+
ops.pop();
29+
}
30+
ops.pop();
31+
} else {
32+
assert(c == '+' || c == '-' || c == '*' || c == '/');
33+
while (!ops.empty() && (ops.top() != '(' && prec[ops.top()] >= prec[c])) {
34+
output.push(ops.top());
35+
ops.pop();
36+
}
37+
ops.push(c);
38+
}
39+
}
40+
while (!ops.empty()) {
41+
assert(ops.top() != '(' && ops.top() != ')');
42+
output.push(ops.top());
43+
ops.pop();
44+
}
45+
46+
stack<int> st;
47+
while (!output.empty()) {
48+
c = output.front();
49+
output.pop();
50+
if (isdigit(c)) {
51+
st.push(c - '0');
52+
} else {
53+
int x, y;
54+
y = st.top(); st.pop();
55+
x = st.top(); st.pop();
56+
if (c == '+') {
57+
st.push(x + y);
58+
} else if (c == '-') {
59+
st.push(x - y);
60+
} else if (c == '/') {
61+
st.push(x / y);
62+
} else {
63+
st.push(x * y);
64+
}
65+
}
66+
}
67+
return st.top();
68+
}
69+
70+
int main() {
71+
string input;
72+
getline(cin, input);
73+
stringstream ss(input);
74+
int val = shuntyard(ss);
75+
cout << input << " = " << val << endl;
76+
return 0;
77+
}

0 commit comments

Comments
 (0)