-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.cpp
102 lines (99 loc) · 2.42 KB
/
parse.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
#include"parse.h"
using namespace std;
int number_from_pos(string form, int& index)
{
if (index < 0 || index >= form.length())
{
return 0;
}
int res = 0;
while (isdigit(form.at(index)))
{
res *= 10;
res += (form[index] - '0');
if (++index >= form.length())
{
break;
}
}
return res;
}
vector<int> parse_from_pos(string form, vector<element> e, int& index)
{
int i = index;
vector<int> result;
vector<int> tmpres;
result.resize(e.size());
tmpres.resize(e.size());
if (i >= form.size())
{
cerr << "Index greater than size of formula!" << endl;
}
else if (i < 0)
{
cerr << "Index is negative!" << endl;
}
while (i < form.size())
{
char c = form[i];
if (c == '(')
{
i++;
tmpres = parse_from_pos(form, e, i);
// i now points at the first character *AFTER* closing parenthesis
if (i < form.size() && isdigit(form[i]))
{
int multiply = number_from_pos(form, i);
mulv(tmpres, multiply);
}
}
else if (c == ')')
{
i++;
break;
}
else if (isalpha(c))
{
string z;
while (i < form.size() && isalpha(c = form[i++]))
{
z.push_back(c);
int fi;
if ((fi = find_symbol(e, z)) != -1)
{
bool flag = false;
flag |= (i >= form.size());
if (i < form.size())
{
flag |= !islower(form[i]);
}
if (flag)
{
tmpres[fi]++;
break;
}
}
}
if (isdigit(form[i]))
{
int multiply = number_from_pos(form, i);
mulv(tmpres, multiply);
}
}
addv(result, tmpres);
tmpres.clear();
tmpres.resize(e.size());
}
index = i;
return result;
}
void parse(string form, vector<element> e, vector<int>& result)
{
int _i = 0;
result = parse_from_pos(form, e, _i);
if (_i != form.length())
{
cerr << "Final index is NOT the length of formula string." << endl;
}
return;
}