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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
| public class Parser
{
public const char START_ARG = '(';
public const char END_ARG = ')';
public const char END_LINE = '\n';
class Cell
{
internal Cell(double value, char action)
{
Value = value;
Action = action;
}
internal double Value { get; set; }
internal char Action { get; set; }
}
public static double process(string data)
{
// Get rid of spaces and check parenthesis
string expression = preprocess(data);
int from = 0;
return loadAndCalculate(data, ref from, END_LINE);
}
static string preprocess(string data)
{
if (string.IsNullOrEmpty(data))
{
throw new ArgumentException("Loaded empty data");
}
int parentheses = 0;
StringBuilder result = new StringBuilder(data.Length);
for (int i = 0; i < data.Length; i++)
{
char ch = data[i];
switch (ch)
{
case ' ':
case '\t':
case '\n': continue;
case END_ARG: parentheses--;
break;
case START_ARG: parentheses++;
break;
}
result.Append(ch);
}
if (parentheses != 0)
{
throw new ArgumentException("Uneven parenthesis");
}
return result.ToString();
}
public static double loadAndCalculate(string data, ref int from, char to = END_LINE)
{
if (from >= data.Length || data[from] == to)
{
throw new ArgumentException("Loaded invalid data: " + data);
}
List<Cell> listToMerge = new List<Cell>(16);
StringBuilder item = new StringBuilder();
do
{ // Main processing cycle of the first part.
char ch = data[from++];
if (stillCollecting(item.ToString(), ch, to))
{ // The char still belongs to the previous operand.
item.Append(ch);
if (from < data.Length && data[from] != to)
{
continue;
}
}
// We are done getting the next token. The getValue() call below may
// recursively call loadAndCalculate(). This will happen if extracted
// item is a function or if the next item is starting with a START_ARG '('.
ParserFunction func = new ParserFunction(data, ref from, item.ToString(), ch);
double value = func.getValue(data, ref from);
char action = validAction(ch) ? ch
: updateAction(data, ref from, ch, to);
listToMerge.Add(new Cell(value, action));
item.Clear();
} while (from < data.Length && data[from] != to);
if (from < data.Length &&
(data[from] == END_ARG || data[from] == to))
{ // This happens when called recursively: move one char forward.
from++;
}
Cell baseCell = listToMerge[0];
int index = 1;
return merge(baseCell, ref index, listToMerge);
}
static bool stillCollecting(string item, char ch, char to)
{
// Stop collecting if either got END_ARG ')' or to char, e.g. ','.
char stopCollecting = (to == END_ARG || to == END_LINE) ?
END_ARG : to;
return (item.Length == 0 && (ch == '-' || ch == END_ARG)) ||
!(validAction(ch) || ch == START_ARG || ch == stopCollecting);
}
static bool validAction(char ch)
{
return ch == '*' || ch == '/' || ch == '+' || ch == '-' || ch == '^';
}
static char updateAction(string item, ref int from, char ch, char to)
{
if (from >= item.Length || item[from] == END_ARG || item[from] == to)
{
return END_ARG;
}
int index = from;
char res = ch;
while (!validAction(res) && index < item.Length)
{ // Look for the next character in string until a valid action is found.
res = item[index++];
}
from = validAction(res) ? index
: index > from ? index - 1
: from;
return res;
}
// From outside this function is called with mergeOneOnly = false.
// It also calls itself recursively with mergeOneOnly = true, meaning
// that it will return after only one merge.
static double merge(Cell current, ref int index, List<Cell> listToMerge,
bool mergeOneOnly = false)
{
while (index < listToMerge.Count)
{
Cell next = listToMerge[index++];
while (!canMergeCells(current, next))
{ // If we cannot merge cells yet, go to the next cell and merge
// next cells first. E.g. if we have 1+2*3, we first merge next
// cells, i.e. 2*3, getting 6, and then we can merge 1+6.
merge(next, ref index, listToMerge, true /* mergeOneOnly */);
}
mergeCells(current, next);
if (mergeOneOnly)
{
return current.Value;
}
}
return current.Value;
}
static void mergeCells(Cell leftCell, Cell rightCell)
{
switch (leftCell.Action)
{
case '^': leftCell.Value = Math.Pow(leftCell.Value, rightCell.Value);
break;
case '*': leftCell.Value *= rightCell.Value;
break;
case '/':
if (rightCell.Value == 0)
{
throw new ArgumentException("Division by zero");
}
leftCell.Value /= rightCell.Value;
break;
case '+': leftCell.Value += rightCell.Value;
break;
case '-': leftCell.Value -= rightCell.Value;
break;
}
leftCell.Action = rightCell.Action;
}
static bool canMergeCells(Cell leftCell, Cell rightCell)
{
return getPriority(leftCell.Action) >= getPriority(rightCell.Action);
}
static int getPriority(char action)
{
switch (action) {
case '^': return 4;
case '*':
case '/': return 3;
case '+':
case '-': return 2;
}
return 0;
}
}
public class ParserFunction
{
public ParserFunction()
{
m_impl = this;
}
// A "virtual" Constructor
internal ParserFunction(string data, ref int from, string item, char ch)
{
if (item.Length == 0 && ch == Parser.START_ARG)
{
// There is no function, just an expression in parentheses
m_impl = s_idFunction;
return;
}
if (m_functions.TryGetValue(item, out m_impl))
{
// Function exists and is registered (e.g. pi, exp, etc.)
return;
}
// Function not found, will try to parse this as a number.
s_strtodFunction.Item = item;
m_impl = s_strtodFunction;
}
public static void addFunction(string name, ParserFunction function)
{
m_functions[name] = function;
}
public double getValue(string data, ref int from)
{
return m_impl.evaluate(data, ref from);
}
protected virtual double evaluate(string data, ref int from)
{
// The real implementation will be in the derived classes.
return 0;
}
private ParserFunction m_impl;
private static Dictionary<string, ParserFunction> m_functions = new Dictionary<string, ParserFunction>();
private static StrtodFunction s_strtodFunction = new StrtodFunction();
private static IdentityFunction s_idFunction = new IdentityFunction();
}
class StrtodFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double num;
if (!Double.TryParse(Item, out num)) {
throw new ArgumentException("Could not parse token [" + Item + "]");
}
return num;
}
public string Item { private get; set; }
}
class IdentityFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
return Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
}
}
class PiFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
return 3.141592653589793;
}
}
class ExpFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
return Math.Exp(arg);
}
}
class PowFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double arg1 = Parser.loadAndCalculate(data, ref from, ',');
double arg2 = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
return Math.Pow(arg1, arg2);
}
}
class SinFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
return Math.Sin(arg);
}
}
class SqrtFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
return Math.Sqrt(arg);
}
}
class AbsFunction : ParserFunction
{
protected override double evaluate(string data, ref int from)
{
double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
return Math.Abs(arg);
}
} |