-
Notifications
You must be signed in to change notification settings - Fork 4
/
ArithmeticalExpressionCalc.cs
335 lines (302 loc) · 10.4 KB
/
ArithmeticalExpressionCalc.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
/*
* *Write a program that calculates the value of given arithmetical expression.
* The expression can contain the following elements only:
* Real numbers, e.g. 5, 18.33, 3.14159, 12.6
* Arithmetic operators: +, -, *, / (standard priorities)
* Mathematical functions: ln(x), sqrt(x), pow(x,y)
* Brackets (for changing the default priorities)
* Examples:
* (3+5.3) * 2.7 - ln(22) / pow(2.2, -1.7) -> ~ 10.6
* pow(2, 3.14) * (3 - (3 * sqrt(2) - 3.2) + 1.5*0.3) -> ~ 21.22
* Hint: Use the classical "shunting yard" algorithm and "reverse Polish notation".
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class ArithmeticalExpressionCalc
{
public static List<char> arithmeticOperations = new List<char> { '+', '-', '*', '/' };
public static List<char> brackets = new List<char>() { '(', ')' };
public static List<string> functions = new List<string>() { "pow", "sqrt", "ln" };
static string TrimInput(string expression)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] != ' ')
{
result.Append(expression[i]);
}
}
return result.ToString();
}
static List<string> SeparateTokens(string expression)
{
var result = new List<string>();
var number = new StringBuilder();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '-' && (i == 0 || expression[i - 1] == ',' || expression[i - 1] == '('))
{
number.Append('-');
}
else if (char.IsDigit(expression[i]) || expression[i] == '.')
{
number.Append(expression[i]);
}
else if (!char.IsDigit(expression[i]) && expression[i] != '.' && number.Length != 0)
{
result.Add(number.ToString());
number.Clear();
i--;
}
else if (brackets.Contains(expression[i]))
{
result.Add(expression[i].ToString());
}
else if (arithmeticOperations.Contains(expression[i]))
{
result.Add(expression[i].ToString());
}
else if (expression[i] == ',')
{
result.Add(",");
}
else if (i + 1 < expression.Length && expression.Substring(i, 2).ToLower() == "ln")
{
result.Add("ln");
i++;
}
else if (i + 2 < expression.Length && expression.Substring(i, 3).ToLower() == "pow")
{
result.Add("pow");
i += 2;
}
else if (i + 3 < expression.Length && expression.Substring(i, 4).ToLower() == "sqrt")
{
result.Add("sqrt");
i += 3;
}
else
{
throw new ArgumentException("Invalid expression.");
}
}
if (number.Length != 0)
{
result.Add(number.ToString());
}
return result;
}
static int Precedence(string arithmeticOperator)
{
if (arithmeticOperator == "+" || arithmeticOperator == "-")
{
return 1;
}
else
{
return 2;
}
}
static Queue<string> ConvertToReversePolishNotation(List<string> tokens)
{
Stack<string> stack = new Stack<string>();
Queue<string> queue = new Queue<string>();
for (int i = 0; i < tokens.Count; i++)
{
var currentToken = tokens[i];
double number;
if(double.TryParse(currentToken, out number))
{
queue.Enqueue(currentToken);
}
else if (functions.Contains(currentToken))
{
stack.Push(currentToken);
}
else if (currentToken == ",")
{
if(!stack.Contains("(") || stack.Count == 0)
{
throw new ArgumentException("Invalid brackets or function separator");
}
while (stack.Peek() != "(")
{
// if not working -> you may need to pop the "("
queue.Enqueue(stack.Pop());
}
}
else if (arithmeticOperations.Contains(currentToken[0]))
{
// if not working -> refactor logic for currentToken
while (stack.Count != 0 && arithmeticOperations.Contains(stack.Peek()[0]) && Precedence(currentToken) <= Precedence(stack.Peek()))
{
queue.Enqueue(stack.Pop());
}
stack.Push(currentToken);
}
else if (currentToken == "(")
{
stack.Push("(");
}
else if (currentToken == ")")
{
if (!stack.Contains("(") || stack.Count == 0)
{
throw new ArgumentException("Invalid brackets.");
}
while (stack.Peek() != "(")
{
queue.Enqueue(stack.Pop());
}
stack.Pop();
if (stack.Count != 0 && functions.Contains(stack.Peek()))
{
queue.Enqueue(stack.Pop());
}
}
}
while (stack.Count != 0)
{
if(brackets.Contains(stack.Peek()[0]))
{
throw new ArgumentException("Invalid bracket.");
}
queue.Enqueue(stack.Pop());
}
return queue;
}
static void PutInvariantCulture()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
static double GetResultFromRPN(Queue<string> queue)
{
Stack<double> stack = new Stack<double>();
while (queue.Count != 0)
{
double number;
string currentToken = queue.Dequeue();
if (double.TryParse(currentToken, out number))
{
stack.Push(number);
}
else if(arithmeticOperations.Contains(currentToken[0]) || functions.Contains(currentToken))
{
if (currentToken == "+")
{
if (stack.Count < 2)
{
throw new ArgumentException("Invalid expression.");
}
double firstValue = stack.Pop();
double secondValue = stack.Pop();
stack.Push(firstValue + secondValue);
}
else if (currentToken == "-")
{
if (stack.Count < 2)
{
throw new ArgumentException("Invalid expression.");
}
double firstValue = stack.Pop();
double secondValue = stack.Pop();
stack.Push(secondValue - firstValue);
}
else if (currentToken == "*")
{
if (stack.Count < 2)
{
throw new ArgumentException("Invalid expression.");
}
double firstValue = stack.Pop();
double secondValue = stack.Pop();
stack.Push(secondValue * firstValue);
}
else if (currentToken == "/")
{
if (stack.Count < 2)
{
throw new ArgumentException("Invalid expression.");
}
double firstValue = stack.Pop();
double secondValue = stack.Pop();
stack.Push(secondValue / firstValue);
}
else if (currentToken == "pow")
{
if (stack.Count < 2)
{
throw new ArgumentException("Invalid expression.");
}
double firstValue = stack.Pop();
double secondValue = stack.Pop();
stack.Push(Math.Pow(secondValue, firstValue));
}
else if(currentToken == "sqrt")
{
if(stack.Count < 1)
{
throw new ArgumentException("Invalid expression.");
}
double value = stack.Pop();
stack.Push(Math.Sqrt(value));
}
else if(currentToken == "ln")
{
if(stack.Count < 1)
{
throw new ArgumentException("Invalid expression.");
}
double value = stack.Pop();
stack.Push(Math.Log(value));
}
}
}
if(stack.Count == 1)
{
return stack.Pop();
}
else
{
throw new ArgumentException("Invalid expression.");
}
}
static void StartCalculating()
{
Console.WriteLine("To end this program enter \"end\"(without quotes)");
Console.Write("Enter expression:");
string expression = Console.ReadLine();
while (expression != "end")
{
try
{
string trimmedInput = expression.Replace(" ", string.Empty);
var separateTokens = SeparateTokens(trimmedInput);
var reversePolishNotation = ConvertToReversePolishNotation(separateTokens);
var finalResult = GetResultFromRPN(reversePolishNotation);
Console.WriteLine(finalResult);
}
catch (ArgumentException ae)
{
Console.Error.WriteLine(ae.Message);
}
catch (FormatException fe)
{
Console.Error.WriteLine(fe.Message);
}
Console.Write("Enter expression:");
expression = Console.ReadLine();
}
}
static void Main(string[] args)
{
PutInvariantCulture();
StartCalculating();
}
}