-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCalculator.cs
337 lines (318 loc) · 13 KB
/
Calculator.cs
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
332
333
334
335
336
337
/*
Copyright (c) 2011-2012, Måns Andersson <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using Calculator.Operands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Calculator
{
/// <summary>
/// Modes to operate calculator in
/// </summary>
public enum CalculatorMode
{
/// <summary>Mathematics mode of calculator (XOR=XOR, AND=AND and so on, all division is floating point)</summary>
Mathematics,
/// <summary>Programming mode of calculator (XOR=^, AND=& and so on, all division is treated like in programming (e.g. int/int gives int)</summary>
Programming,
}
/// <summary>
/// Calculator execution class
/// </summary>
public class Calculator
{
/// <summary>
/// Different types of tokens for quick identification
/// </summary>
private enum TokenType
{
/// <summary>Operator</summary>
Operator,
/// <summary>Left Parenthesis</summary>
LeftParenthesis,
/// <summary>RightParenthesis</summary>
RightParenthesis,
/// <summary>Value</summary>
Value,
/// <summary>Function</summary>
Function,
}
private string _input = null;
/// <summary>
/// Regular expression used for splitting the expression into tokens
/// </summary>
public string TokenSplitRegex
{
get
{
switch (Mode)
{
default:
case CalculatorMode.Mathematics:
return @"( AND | OR | XOR | NOT |[\+\-\*\^\(\)\/\ ])";
case CalculatorMode.Programming:
return @"(<<|>>|[%\+\-\*\&\|\^\(\)\/\ ])";
}
}
}
/// <summary>
/// Current mode to operate after
/// </summary>
public CalculatorMode Mode { get; set; }
/// <summary>
/// Constructor, initalize expression
/// </summary>
/// <param name="input">expression to evaluate with calculator</param>
public Calculator(string input)
{
_input = input;
Mode = CalculatorMode.Mathematics;
}
/// <summary>
/// Evaluate expression with Dijkstra's Shunting Yard Algorithm
/// </summary>
/// <returns>result of calculations</returns>
public double? Calculate()
{
if (_input == null)
throw new ArgumentException();
Stack<Op> operatorStack = new Stack<Op>();
Queue<Op> outputQueue = new Queue<Op>();
// Let's split the input string into a token list
List<String> tokenList = Regex.Split(_input, TokenSplitRegex).Select(t => t.Trim()).Where(t => !String.IsNullOrEmpty(t)).ToList();
for (int tokenNum = 0; tokenNum < tokenList.Count(); ++tokenNum)
{
double? tmpValue;
String token = tokenList[tokenNum];
TokenType tokenType = GetTokenType(token, out tmpValue);
// Handle this token and insert into the correct queue or stack
switch (tokenType)
{
case TokenType.Value:
if (tmpValue.HasValue)
outputQueue.Enqueue(new Operand(tmpValue.Value));
else
throw new ArgumentException("Unknown operand " + token);
break;
case TokenType.Operator:
Operator newOperator = GetOperator(token, (tokenNum == 0 || tokenList[tokenNum - 1] == "("));
if (operatorStack.Count > 0)
{
Op topOperator = operatorStack.Peek();
if (topOperator is Operator)
{
if (newOperator.Precedence <= ((Operator)topOperator).Precedence)
{
outputQueue.Enqueue(operatorStack.Pop());
}
}
}
operatorStack.Push(newOperator);
break;
case TokenType.LeftParenthesis:
operatorStack.Push(new LeftParenthesis());
break;
case TokenType.RightParenthesis:
// Handle all operators in the stack (i.e. move them to the outputQueue)
// until we find the LeftParenthesis
while (!(operatorStack.Peek() is LeftParenthesis))
{
outputQueue.Enqueue(operatorStack.Pop());
}
operatorStack.Pop();
break;
case TokenType.Function:
if ((tokenList.Count >= tokenNum + 1) && (tokenList[tokenNum + 1] == "("))
{
Function.FunctionTypes type = Function.GetFunctionType(token);
if (type == Function.FunctionTypes.UNKNOWN)
{
throw new ArgumentException("Unknown function " + token);
}
operatorStack.Push(new Function(type));
}
break;
}
// If we don't find any token between a value and parenthesis, automatically
// add a multiply sign
if (tokenType == TokenType.Value || tokenType == TokenType.RightParenthesis)
{
if (tokenNum < tokenList.Count() - 1)
{
String nextToken = tokenList[tokenNum + 1];
TokenType nextTokenType = GetTokenType(nextToken, out tmpValue);
if (nextTokenType != TokenType.Operator && nextTokenType != TokenType.RightParenthesis)
{
tokenList.Insert(tokenNum + 1, "*");
}
}
}
}
// Move all operators into the outputqueue
while (operatorStack.Count > 0)
{
Op operand = operatorStack.Pop();
if (operand is LeftParenthesis || operand is RightParenthesis)
{
throw new ArgumentException("Mismatched parentheses");
}
outputQueue.Enqueue(operand);
}
// Now we have the expression in reverse polish notation and it's easy to calculate
// Step through the outputQueue and calculate the result
Stack<Operand> outputStack = new Stack<Operand>();
while (outputQueue.Count > 0)
{
Op currentOp = outputQueue.Dequeue();
if (currentOp is Operand)
{
outputStack.Push((Operand)currentOp);
}
else if (currentOp is Operator)
{
Operator currentOperator = (Operator)currentOp;
currentOperator.Execute(outputStack, this.Mode);
}
}
// If we haven't got only one answer, the formula is invalid, return that.
if (outputStack.Count != 1)
{
throw new ArgumentException("Invalid formula");
}
// Pop and return the result
return outputStack.Pop().Value;
}
/// <summary>
/// Checks which token type a token belongs to
/// </summary>
/// <param name="token">token to check</param>
/// <returns>the token type for the token</returns>
private TokenType GetTokenType(string token, out double? value)
{
if ((value = Operand.ParseValue(token)) != null)
{
return TokenType.Value;
}
else if (token == "(")
{
return TokenType.LeftParenthesis;
}
else if (token == ")")
{
return TokenType.RightParenthesis;
}
else if (token == "+" ||
token == "-" ||
token == "*" ||
token == "/" ||
token == "^" ||
token == "&" ||
token == "|" ||
token == "%" ||
token == "<<" ||
token == ">>" ||
token == "AND" ||
token == "OR" ||
token == "XOR" ||
token == "NOT")
{
return TokenType.Operator;
}
else if (Regex.IsMatch(token, @"^[0-9A-Za-z]+$"))
{
return TokenType.Function;
}
else
{
throw new ArgumentException("Invalid token");
}
}
/// <summary>
/// Get an operator object representing a token
/// </summary>
/// <param name="token">token to represent as an object</param>
/// <param name="isFirstToken">whether this token is the first (first in expression, or first after a new sub-expression)</param>
/// <returns>operator object corresponding to token</returns>
private Operator GetOperator(string token, bool isFirstToken)
{
if (this.Mode == CalculatorMode.Mathematics)
{
switch (token)
{
case "+":
return new Plus();
case "-":
if (isFirstToken)
return new Negative();
else
return new Minus();
case "*":
return new Multiplication();
case "/":
return new Div();
case "^":
return new Exponent();
case "AND":
return new And();
case "OR":
return new Or();
case "XOR":
return new Xor();
case "NOT":
return new Not();
default:
throw new ArgumentException("Unknown operator " + token);
}
}
else if (this.Mode == CalculatorMode.Programming)
{
switch (token)
{
case "+":
return new Plus();
case "-":
if (isFirstToken)
return new Negative();
else
return new Minus();
case "*":
return new Multiplication();
case "/":
return new Div();
case "<<":
return new LeftShift();
case ">>":
return new RightShift();
case "%":
return new Modulus();
case "&":
return new And();
case "|":
return new Or();
case "^":
return new Xor();
case "~":
return new Not();
default:
throw new ArgumentException("Unknown operator " + token);
}
}
else
{
throw new ArgumentException("Unknown calculator mode");
}
}
}
}