-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
467 lines (435 loc) · 14.1 KB
/
main.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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include <iostream>
#include <string.h>
#include <string>
#include <iomanip>
#include <cstdio>
#include <sstream>
#include <vector>
#include <stdexcept>
using namespace std;
#include "stack.cpp"
#include <stdlib.h>
vector<string> in2post(vector<string>&);
vector<string> in2pre(vector<string>&);
string post2in(vector<string>);
string pre2in(vector<string>);
vector<string> stringToInfix(string&);
vector<string> stringToVector(string&);
void printTerm(vector<string>&);
string evalExp(vector<string>);
bool isDigit(const string& str)
{
string::const_iterator iter = str.begin();
for(; isdigit(*iter) && iter != str.end(); iter++);
return !str.empty() && iter == str.end();
}
bool isOperator(const string& str)
{
string::const_iterator iter = str.begin();
return !str.empty() && str.size() == 1 &&
(*iter == '*' || *iter == '+' || *iter == '-' || *iter == '/');
}
bool precedeOperator(const string& first, const string& second)
{
if (first == "+" || first == "-")
return isOperator(second);
else if (first == "*" || first == "/")
return second == "*" || second == "/";
else if (first == "^")
return second == "^";
}
vector<string> getReverse(vector<string>& str)
{
vector<string> z;
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == "(")
z.push_back(")");
else if (str[i] == ")")
z.push_back("(");
else
z.push_back(str[i]);
}
return z;
}
int main()
{
do
{
string head(76, '*'), middle(25, '*');
string pressKey = "Press any key to continue...\n";
system("clear");
cout << head << endl;
cout << middle << " Prefix Infix Postfix " << middle << endl;
cout << head << endl;
cout << "1. I want to enter a prefix term." << endl
<< "2. I want to enter an infix term." << endl
<< "3. I want to enter a postfix term." << endl
<< "default. Exit." << endl
<< "Enter your selection: ";
int input;
cin >> input;
vector<string> postExpr;
try
{
string term;
vector<string> inputTerm;
vector<string> inToPre, inToPost;
string postToIn, preToIn;
switch (input)
{
case 1:
cout << "Enter your prefix term: ";
cin.ignore();
getline(cin, term);
inputTerm = stringToVector(term);
cout << "Equivalent infix term:\n";
preToIn = pre2in(inputTerm);
inputTerm = stringToInfix(preToIn);
printTerm(inputTerm);
cout << "Equivalent postfix term:\n";
inToPost = in2post(inputTerm);
printTerm(inToPost);
postExpr = inToPost;
break;
case 2:
cout << "Enter your infix term: ";
cin.ignore();
getline(cin, term);
inputTerm = stringToInfix(term);
cout << "Equivalent prefix term:\n";
inToPre = in2pre(inputTerm);
printTerm(inToPre);
cout << "Equivalent postfix term:\n";
inToPost = in2post(inputTerm);
printTerm(inToPost);
postExpr = inToPost;
break;
case 3:
cout << "Enter your postfix term: ";
cin.ignore();
getline(cin, term);
inputTerm = stringToVector(term);
postExpr = inputTerm;
cout << "Equivalent infix term:\n";
postToIn = post2in(inputTerm);
inputTerm = stringToInfix(postToIn);
inputTerm = getReverse(inputTerm);
printTerm(inputTerm);
cout << "Equivalent prefix term:\n";
inToPre = in2pre(inputTerm);
printTerm(inToPre);
break;
default:
return 0;
}
}
catch (const invalid_argument &ex)
{
cerr << ex.what() << endl;
return 1;
}
cout << "The evaluation of the expression is: " << evalExp(postExpr) << endl;
cout << pressKey;
cin.get();
} while (true);
}
vector<string> stringToInfix(string& str)
{
vector<string> result;
string tmp = "";
short openParantheses = 0;
for (int i = 0; i < str.size(); i++)
{
char localTmp = str[i];
string lastOp = "";
if (result.size() > 0)
lastOp = *(result.end() - 1);
if (localTmp >= '0' && localTmp <= '9')
{
if (lastOp == ")")
throw invalid_argument("number after ')' at position " + i);
tmp += localTmp;
}
else if (localTmp == '+' || localTmp == '-' ||
localTmp == '/' || localTmp == '*')
{
if (tmp == "")
{
if (result.empty())
throw invalid_argument("operator in the beginning of the input at position " + i);
else if (lastOp == "+" || lastOp == "-" ||
lastOp == "*" || lastOp == "/")
throw invalid_argument("operator after operator at position " + i);
else if (lastOp == "(")
throw invalid_argument("operator after '(' at position " + i);
}
else // if (tmp != "")
{
result.push_back(tmp);
tmp = "";
}
result.push_back(string(1, localTmp));
}
else if (localTmp == '(')
{
openParantheses++;
if (tmp != "")
throw invalid_argument("'(' after number at position " + i);
else if (lastOp == ")")
throw invalid_argument("'(' after ')' at position " + i);
result.push_back(string(1, localTmp));
}
else if (localTmp == ')')
{
if (openParantheses == 0)
throw invalid_argument("number of ')' is more that '(' at position" + i);
if (tmp != "")
{
result.push_back(tmp);
tmp = "";
}
result.push_back(string(1, localTmp));
openParantheses--;
}
}
if (tmp != "")
result.push_back(tmp);
if (openParantheses > 0)
throw invalid_argument("number of '(' more that ')' at the end of the input");
return result;
}
vector<string> stringToVector(string& str)
{
vector<string> result;
string tmp = "";
short openParantheses = 0;
for (int i = 0; i < str.size(); i++)
{
char localTmp = str[i];
string lastOp = "";
if (!result.empty())
lastOp = *(result.end() - 1);
if (localTmp == ' ' || localTmp == '\t')
{
if (tmp != "")
{
result.push_back(tmp);
tmp = "";
}
continue;
}
else if (localTmp >= '0' && localTmp <= '9')
{
tmp += localTmp;
}
else if (localTmp == '+' || localTmp == '-' ||
localTmp == '/' || localTmp == '*')
{
if (tmp != "")
{
result.push_back(tmp);
tmp = "";
}
result.push_back(string(1, localTmp));
}
else if (localTmp == '(')
{
openParantheses++;
result.push_back(string(1, localTmp));
}
else if (localTmp == ')')
{
if (tmp != "")
{
result.push_back(tmp);
tmp = "";
}
result.push_back(string(1, localTmp));
openParantheses--;
}
}
if (tmp != "")
result.push_back(tmp);
if (openParantheses > 0)
throw invalid_argument("number of '(' more that ')' at the end of the input");
return result;
}
void printTerm(vector<string>& input)
{
for (unsigned int i = 0; i < input.size(); i++)
cout << input[i] << setw(2);
cout << endl;
}
// ========================================== infix to others ===================================================
vector<string> in2post(vector<string>& x)
{
vector<string> y; // the equivalent postfix expression
stack<string> opStack;
// step 1: Push “(“onto Stack, and add “)” to the end of X.
opStack.push("(");
x.push_back(")");
// step 2: Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
for (vector<string>::const_iterator iter = x.begin();
iter != x.end();
iter++)
{
// step 3: If an operand is encountered, add it to Y.
if (isDigit(*iter))
y.push_back(*iter);
// step 4: If a left parenthesis is encountered, push it onto Stack.
else if (*iter == "(")
opStack.push(*iter);
// step 5: If an operator is encountered ,then:
else if (isOperator(*iter))
{
// step 5.1: Repeatedly pop from Stack and add to Y each operator (on the top of Stack)
// which has the same precedence as or higher precedence than operator.
while (true)
{
string lastOperator = opStack.top();
if (precedeOperator(*iter, lastOperator))
{
y.push_back(lastOperator);
opStack.pop();
}
else
break;
}
// step 5.2: Add operator to Stack.
opStack.push(*iter);
}
// step 6: If a right parenthesis is encountered ,then:
else if (*iter == ")")
{
// step 6.1: Repeatedly pop from Stack and add to Y each operator (on the top of Stack)
// until a left parenthesis is encountered.
while (true)
{
string lastOperator = opStack.top();
if (lastOperator != "(")
{
y.push_back(lastOperator);
opStack.pop();
}
else
break;
}
// step 6.2: Remove the left Parenthesis.
opStack.pop();
}
}
while (!opStack.isEmpty())
{
string lastOperator = opStack.top();
if (lastOperator != "(")
y.push_back(lastOperator);
opStack.pop();
}
// END
return y;
}
vector<string> in2pre(vector<string>& x)
{
/* 1. get the infix expression
* 2. reverse the infix notation
* 3. get the equivalent postfix notation of result from step 2 (in2post)
* 4. reverse the expression from step 3 to some y
* 5. the result is in y and can be used accordingly
*/
vector<string> reverse = getReverse(x);
vector<string> y = in2post(reverse);
return getReverse(y);
}
string post2in(vector<string> x)
{
/* Algorithm
1.While there are input symbol left
1.1 Read the next symbol from the input.
2.If the symbol is an operand
2.1 Push it onto the stack.
3.Otherwise,
3.1 the symbol is an operator.
3.2 Pop the top 2 values from the stack.
3.3 Put the operator, with the values as arguments and form a string.
3.4 Push the resulted string back to stack.
4.If there is only one value in the stack
4.1 That value in the stack is the desired infix string. */
stack<string> opStack;
for (vector<string>::const_iterator iter = x.begin(); iter != x.end(); iter++)
{
if (isDigit(*iter)) // step 2
opStack.push(*iter);
else if (isOperator(*iter)) // step 3
{
string op1 = opStack.top();
opStack.pop();
string op2 = opStack.top();
opStack.pop();
string result = "(" + op1 + *iter + op2 + ")";
opStack.push(result);
}
}
if (opStack.getSize() == 1)
return opStack.top();
}
string pre2in(vector<string> x)
{
/* 1. Read the Prefix expression in reverse order (from right to left)
2. If the symbol is an operand, then push it onto the Stack
3. If the symbol is an operator, then pop two operands from the Stack
4. Create a string by concatenating the two operands and the operator between them.
5. string = (operand1 + operator + operand2)
6. And push the resultant string back to Stack
7. Repeat the above steps until end of Prefix expression.*/
x = getReverse(x);
stack<string> opStack;
for (vector<string>::const_iterator iter = x.begin(); iter != x.end(); iter++)
{
if (isDigit(*iter))
opStack.push(*iter);
else if (isOperator(*iter))
{
string op1 = opStack.top();
opStack.pop();
string op2 = opStack.top();
opStack.pop();
string res = "(" + op1 + *iter + op2 + ")";
opStack.push(res);
}
}
if (opStack.getSize() == 1)
return opStack.top();
}
string evalExp(vector<string> postfixTerm)
{
stack<string> opStack;
for (vector<string>::const_iterator iter = postfixTerm.begin(); iter != postfixTerm.end(); iter++)
{
if (isDigit(*iter)) // step 2
opStack.push(*iter);
else if (isOperator(*iter)) // step 3
{
string op2 = opStack.top();
opStack.pop();
string op1 = opStack.top();
opStack.pop();
float res = 0.0;
float operand1 = strtof(op1.c_str(), 0),
operand2 = strtof(op2.c_str(), 0);
if (*iter == "+")
res = operand1 + operand2;
else if (*iter == "-")
res = operand1 - operand2;
else if (*iter == "*")
res = operand1 * operand2;
else if (*iter == "/")
res = operand1 / operand2;
stringstream ss;
ss << fixed << setprecision(2) << res;
opStack.push(ss.str());
}
}
if (opStack.getSize() == 1)
return opStack.top();
}