-
Notifications
You must be signed in to change notification settings - Fork 1
/
Calculator.cs
288 lines (240 loc) · 10.5 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Calculator
{
class Calculator
{
private double prevNumber(ref String text, int index, out int from)
{
double prev = 0.0;
int i;
for (i = index; i > -1; i--)
//p: is number, q: dot, r: minus sign, k: minus in 0
// p + q + (r * k)
// ~p * ~q * (~r + ~k)
if (!Char.IsDigit(text[i]) && text[i] != '.' && (text[i] != '-' || i != 0))
break;
prev = double.Parse(text.Substring(i + 1, index - i));
from = i + 1;
return prev;
}
private double nextNumber(ref String text, int index, out int to)
{
double next = 0.0;
int i;
for (i = index; i < text.Length; i++)
if (!Char.IsDigit(text[i]) && text[i] != '.' && (text[i] != '-' //1+-2-5 d+.+(-*p) -d*-.*(--+)
|| Char.IsDigit(text[i - 1])))
break;
next = double.Parse(text.Substring(index, i - index));
to = i;
return next;
}
private string getNextOperand(string text)
{
if (text.Contains("^")) return "^";
else if (text.Contains("/")) return "/";
else if (text.Contains("*")) return "*";
else if (text.Contains("-") && text.LastIndexOf("-") != 0
&& Char.IsDigit(text[text.LastIndexOf("-") - 1])) return "-";
else if (text.Contains("+")) return "+";
else return null;
}
private int getIndexOfOperand(string text, string operand)
{
if (operand.Equals("-")) return text.IndexOf("-", 1); // ignore the minus sign if it was at the beginning (-1+2)
else return text.IndexOf(operand);
}
private double applyOperand(string operand, double firstNumber, double secondNumber)
{
if (operand.Equals("*")) return firstNumber * secondNumber;
else if (operand.Equals("/")) return firstNumber / secondNumber;
else if (operand.Equals("+")) return firstNumber + secondNumber;
else if (operand.Equals("^")) return Math.Pow(firstNumber, secondNumber);
else return firstNumber - secondNumber;
}
private bool contains(string text, string subText)
{
return text.IndexOf(subText, StringComparison.OrdinalIgnoreCase) != -1;
}
private string getNextFunction(string text)
{
if (contains(text, "√")) return "√";
else if (contains(text, "log")) return "log";
else if (contains(text, "arcsin")) return "arcsin";
else if (contains(text, "arccos")) return "arccos";
else if (contains(text, "arctan")) return "arctan";
else if (contains(text, "sin")) return "sin";
else if (contains(text, "cos")) return "cos";
else if (contains(text, "tan")) return "tan";
else return null;
}
private int getFunctionEnd(string text, int startIndex)
{
int count = 0;
int endIndex;
for (endIndex = text.IndexOf('(', startIndex); endIndex < text.Length; endIndex++)
{
if (text[endIndex] == '(') count++;
else if (text[endIndex] == ')') count--;
if (count == 0) break;
}
return endIndex;
}
private double executeFunction(string func, string funcText)
{
int from = funcText.IndexOf('(') + 1;
int to = funcText.LastIndexOf(')') - from;
string textValue = funcText.Substring(from, to);
double value = double.Parse(calc(textValue));
if (func.Equals("√"))
{
int f = funcText.IndexOf('[') + 1;
int t = funcText.IndexOf(']') - f;
double rootBase = double.Parse(funcText.Substring(f, t));
return Math.Pow(value, 1 / rootBase);
}
else if (func.Equals("log"))
{//e.g: log[10](8+2)
int f = funcText.IndexOf('[') + 1;
int t = funcText.IndexOf(']') - f;
double logBase = double.Parse(funcText.Substring(f, t));
return Math.Log(value, logBase);
}
else if (func.Equals("arcsin")) return Math.Asin(value);
else if (func.Equals("arccos")) return Math.Acos(value);
else if (func.Equals("arctan")) return Math.Atan(value);
else if (func.Equals("sin")) return Math.Sin(value);
else if (func.Equals("cos")) return Math.Cos(value);
else if (func.Equals("tan")) return Math.Tan(value);
else throw new Exception();
}
private void cleanText(ref string text)
{
text = Regex.Replace(text, @"\s+", ""); // remove white spaces
var pattern1 = new Regex(@"\)\d"); // error: (1+2)5
if (pattern1.IsMatch(text)) throw new Exception();
var pattern2 = new Regex(@"!\d"); // error: 2!5
if (pattern2.IsMatch(text)) throw new Exception();
var pattern3 = new Regex(@"π\d"); // error: π5
if (pattern3.IsMatch(text)) throw new Exception();
// number of '(' must be equal to number of ')'
int lp = text.Count(x => x == '(');
int rp = text.Count(x => x == ')');
if (lp != rp) throw new Exception();
text = text.Replace("--", "+");
text = text.Replace("-+", "-");
text = text.Replace("+-", "-");
text = text.Replace("π", "3.1415926535897932384626433832795");
}
private void calcBrackets(ref string text)
{
int startIndex = text.IndexOf('[');
int endIndex, count = 1;
for (endIndex = startIndex + 1; endIndex < text.Length; endIndex++)
{
if (text[endIndex] == '[') count++;
else if (text[endIndex] == ']') count--;
if (count == 0) break;
}
// log[2+1](5)
string baseText = text.Substring(startIndex + 1, endIndex - startIndex - 1);
string func = getNextFunction(baseText);
string op = getNextOperand(baseText);
if (func != null || op != null || baseText.Contains('!'))
{
string tempText = text.Substring(0, startIndex + 1)
+ calc(baseText)
+ text.Substring(endIndex, text.Length - endIndex);
text = tempText;
}
}
private void calcFunction(ref string text, string function)
{
int startIndex = text.IndexOf(function, StringComparison.OrdinalIgnoreCase);
int endIndex = getFunctionEnd(text, startIndex);
string funcText = text.Substring(startIndex, endIndex - startIndex + 1);
string tempText = text.Substring(0, startIndex)
+ ((startIndex > 0 && Char.IsDigit(text[startIndex - 1])) ? "*" : "") // e.g: 5cos(0) = 5*cos(0)
+ executeFunction(function, funcText);
if (endIndex + 1 < text.Length)
tempText += text.Substring(endIndex + 1, text.Length - endIndex - 1);
text = calc(tempText);
}
private void calcParentheses(ref string text)
{
int startIndex = text.IndexOf('(');
int endIndex = text.IndexOf(')');
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '(') startIndex = i;
else if (text[i] == ')')
{
endIndex = i;
string tempText = text.Substring(0, startIndex)
+ ((startIndex > 0 && Char.IsDigit(text[startIndex - 1])) ? "*" : "") // 5(1+2) = 5*(1+2)
+ calc(text.Substring(startIndex + 1, endIndex - startIndex - 1));
if (endIndex + 1 < text.Length)
tempText += text.Substring(endIndex + 1, text.Length - endIndex - 1);
text = calc(tempText);
}
}
}
private void calcFactorial(ref string text)
{
int indx = text.IndexOf("!");
double number = prevNumber(ref text, indx - 1, out int from);
long res = factorial((int)number);
string tempText = text.Substring(0, from) + res + text.Substring(indx + 1, text.Length - indx - 1);
text = calc(tempText);
}
private void calcOperand(ref string text, string operand)
{
int index = getIndexOfOperand(text, operand);
double firstNumber = prevNumber(ref text, index - 1, out int from);
double secondNumber = nextNumber(ref text, index + 1, out int to);
double result = applyOperand(operand, firstNumber, secondNumber);
string tempText = text.Substring(0, from) + result + text.Substring(to, text.Length - to);
text = calc(tempText);
}
private string calc(string text)
{
try
{
cleanText(ref text);
// calculate the base e.g: log[1+1](8) = log[2](8)
if (text.Contains('[')) calcBrackets(ref text);
string function = getNextFunction(text);
if (function != null) calcFunction(ref text, function);
if (text.Contains('(')) calcParentheses(ref text);
if (text.Contains("!")) calcFactorial(ref text);
string operand = getNextOperand(text);
if (operand != null) calcOperand(ref text, operand);
return text;
}
catch (Exception)
{
return "invalid syntax";
}
}
public long factorial(int number)
{
long n = 1;
for (int i = number; i > 1; i--)
n *= i;
return n;
}
public string calculate(string text, out Color color)
{
string result = calc(text);
if (result.Equals("invalid syntax")) color = Color.Red;
else color = Color.Green;
return result;
}
}
}