-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathevaluare.cpp
118 lines (98 loc) · 1.7 KB
/
evaluare.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
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
map<char,unsigned> prec{{'+',0},{'-',0},{'*',1},{'/',1},{'e',100},{')',100}};
struct Token {
char type;
int value;
};
ostream& operator<<(ostream &os, const Token &t) {
if(t.type == 'n') {
os << "n=" << t.value;
}
else {
os << t.type;
}
return os;
}
Token next_token(string::iterator &it) {
switch(*it) {
case '+':
case '*':
case '-':
case '/':
case '(':
case ')':
return {*it++,0};
}
int nr = 0;
while('0' <= *it && *it <= '9') {
nr = nr*10 + (*it-'0');
it++;
}
return {'n',nr};
}
int op(int a, int b, char op) {
switch(op) {
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
cerr << "[op] Expected operator, got " << op << '\n';
}
int eval(vector<Token>::iterator &it,unsigned lvl) {
int res;
if(lvl == 2) {
if(it->type == '(') {
++it;
res = eval(it,0);
++it;
}
else {
if(it->type != 'n') {
cerr << "[eval] Expected number, got " << it->type << '\n';
}
res = it->value;
it++;
}
}
else {
res = eval(it,lvl+1);
while(prec[it->type] == lvl) {
char type = it->type;
it++;
res = op(res,eval(it,lvl+1),type);
}
}
return res;
}
vector<Token> tokenize(string s) {
vector<Token> tokens;
auto it = s.begin();
while(it < s.end()) {
tokens.push_back(next_token(it));
}
tokens.push_back({'e',0});
return move(tokens);
}
int main() {
string s;
in >> s;
vector<Token> tokens = tokenize(s);
// for(Token t:tokens) {
// cout << t << ' ';
// }
auto it = tokens.begin();
out << eval(it,0);
return 0;
}