-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter_coding_exercise_13.cpp
More file actions
85 lines (72 loc) · 1.58 KB
/
Copy pathinterpreter_coding_exercise_13.cpp
File metadata and controls
85 lines (72 loc) · 1.58 KB
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
#include <map>
#include <string>
#include <vector>
#include <regex>
#include <iostream>
using namespace std;
inline vector<string> split(const string& stringToSplit)
{
vector<string> result;
size_t pos = 0, lastPos = 0;
while ((pos = stringToSplit.find_first_of("+-", lastPos)) != string::npos)
{
result.push_back(stringToSplit.substr(lastPos, pos-lastPos+1));
lastPos = pos+1;
}
result.push_back(stringToSplit.substr(lastPos));
return result;
}
struct ExpressionProcessor
{
map<char,int> variables;
enum NextOp
{
nothing,
plus,
minus
};
int calculate(const string& expression)
{
int current;
auto next_op = nothing;
auto parts = split(expression);
cout << "parts (" << parts.size() << "): ";
for (auto& part : parts)
cout << "`" << part << "` ";
cout << endl;
for (auto& part : parts)
{
auto no_op = split(part);
auto first = no_op[0];
int value, z;
try
{
value = stoi(first);
}
catch (const invalid_argument&)
{
if (first.length() == 1 &&
variables.find(first[0]) != variables.end())
{
value = variables[first[0]];
}
else return 0;
}
switch (next_op)
{
case nothing:
current = value;
break;
case plus:
current += value;
break;
case minus:
current -= value;
break;
}
if (*part.rbegin() == '+') next_op = plus;
else if (*part.rbegin() == '-') next_op = minus;
}
return current;
}
};