-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
471 lines (387 loc) · 14.4 KB
/
test.cpp
File metadata and controls
471 lines (387 loc) · 14.4 KB
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
468
469
470
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <vector>
#include <list>
#include <iterator>
#include <map>
#include <cmath>
#include <ctype.h>
#include <typeinfo>
//#include "evaluate.h"
using namespace std;
bool areParanthesisBalanced(string expr);
string lineOperation(string afterEquals);
bool isVariablePresent(string value);
bool isOperatorPresent(string value);
string ReplaceString(string subject, const string& search, const string& replace);
bool isoperator(string str);
void mapEvaluation(string filename, string k);
string evaluate(vector<string> &y);
float eval(float x1, float x2, string sign);
vector<string> tokenize(string x);
int convertOpToInt (string str);
bool isleq(string opA, string opB);
vector<string> infix2postfix(vector<string> &x);
bool isoperator(char ch);
void writeToFile(string line, string filename);
void writeToFile(string line, string filename) {
ofstream myFile;
line+="\n";
myFile.open(filename, std::ofstream::out | std::ofstream::app);
myFile << line;
myFile.close();
}
int main(int count, char * args[]) {
string inputFile = "";
string outputFile = "";
//take as parameters names of the input and output textfiles
for (int i = 1; i < count; i++) {
if ((string(args[i]) == "-i") && i + 1 < count)
inputFile = args[i + 1];
else if ((string(args[i]) == "-o") && i + 1 < count)
outputFile = args[i + 1];
}
//remind user of the way to invocate the application
if (inputFile == "" || outputFile == "") {
cout << "Usage ./mycalc -i <inputfile> -o <outputfile>>" << endl;
return -1;
}
//print out names of the input and output textfiles
cout << "Input file is " << inputFile << endl;
cout << "Output file is " << outputFile << endl;
mapEvaluation(inputFile,outputFile);
}
//Add calculated variables and values to the map
void mapEvaluation(string filename, string outputFile){
ifstream file;
map<string, float> variableMap;
string afterEquals;
string variableName;
int lineNum;
string line;
string cleanExpression;
//get number of lines
file.open(filename);
while (getline(file, line)) {
if (line!=""){
lineNum++;
}
}
file.close();
int k=0;
int fileSize=0;
while((variableMap.size()!=lineNum)&&(fileSize!=lineNum)) {//while not all variables are solved
k++; if(k==1000){break;}
file.open(filename);
string lineString;
int k=0;
while (getline(file, line) and line!="") {
k++; if(k==1000){break;}
/*
evaluation carried on one single expression
*/
variableName = line.substr(0, line.find("=")-1); //variable name
afterEquals = line.substr(line.find("=")+1, line.size()-1); //expression
cleanExpression = lineOperation(afterEquals);//expression manipulation
if(areParanthesisBalanced(cleanExpression)){//sanity check
//cout <<"clean expression is balanced " << cleanExpression << endl;
//update variables with new values
if(!variableMap.empty()) {
map<string, float>::iterator it = variableMap.begin();
while (it != variableMap.end()){
cleanExpression = ReplaceString(cleanExpression, it->first, to_string(it->second));
//cout<<"result of replacement, cleanExpression = "<<cleanExpression<<endl;
it++;
}
}
//postfix calculation
if((not isVariablePresent(cleanExpression)) and (isOperatorPresent(cleanExpression))) {
//cout << variableName << " is being evaluated" << endl;
vector<string> v = tokenize(cleanExpression);//tokenize the expression into vector
for(int i=0; i<v.size();i++){
// cout<<"i: "<<i<<" - " << v[i]<<endl;
}
vector<string> postfix = infix2postfix(v);//postfix expression
string result = evaluate(postfix);//result of calculation
//cout << variableName << " = " << result;
string s = variableName + " = " + result + ";";
if(fileSize<lineNum) {
//writeToFile(s,outputFile);
}
fileSize+=1;
variableMap.insert(make_pair(variableName, stof(result))); //put (variable,value) to map
}
//direct value
else if((not isVariablePresent(cleanExpression)) and (not isOperatorPresent(cleanExpression))) {
string s = variableName + " = " + cleanExpression + ";";
if(fileSize<lineNum) {
// writeToFile(s,outputFile);
}
fileSize+=1;
variableMap.insert(make_pair(variableName, stof(cleanExpression))); //put (variable,value) to map
}
}
/**/
}
//every line of expression has been visited
file.close();
}
map <string, float>::iterator it2 = variableMap.begin();
while (it2 != variableMap.end())
{
string s = it2->first + " = " + to_string(it2->second) + ";";
writeToFile(s,outputFile);
it2++;
}
//calculation completed
map <string, float>::iterator it = variableMap.begin();
while (it != variableMap.end())
{
//cout<< it->first << " = " << it->second <<endl;
it++;
}
}
float eval(float x1, float x2, string sign) {
if (sign == "+")//addition
return x1 + x2;
if (sign == "-")//subtraction
return x1 - x2;
if (sign == "*")//multiplication
return x1 * x2;
if (sign == "/")//division
return x1 / x2;
if (sign == "%")//integer division
return static_cast<int>(x1 / x2);
if (sign == "$")//modulus
return (int)x1 % (int)x2;
}
//Method which will evaluate a PostfixExpression and return the result
string evaluate(vector<string> &y){
//1. Create a stack (e.g. of type float) to store the operands
stack <string> mystack;
//2. Scan the postfix expression from left to right for every element
for (int i = 0; i < y.size(); i++){
// a. if the element is an operand push it to the stack
if (not isoperator(y[i])){
mystack.push(y[i]);
}
else if(y[i]=="^"){
float num = stof(mystack.top())*-1;
mystack.pop();
mystack.push(to_string(num));
}
else if(y[i]=="@"){
float num = stof(mystack.top())-1;
mystack.pop();
mystack.push(to_string(num));
}
else if(y[i]=="#"){
float num = pow(stof(mystack.top()), 2);
mystack.pop();
mystack.push(to_string(num));
}
else if(y[i]=="!"){
float num = stof(mystack.top())+1;
mystack.pop();
mystack.push(to_string(num));
}
// b. if the element is an operator pop 2 elements from the stack,
// apply the operator on it and push the result back to the stack
else{
float x1 = stof(mystack.top());
mystack.pop();
float x2 = stof(mystack.top());
mystack.pop();
float x3 = eval(x2,x1,y[i]);
mystack.push(to_string(x3));
//cout << x2 << " " << x1 << " "<< y[i] << " = " << x3 << endl;
}
}
//3. return the value from the top of the stack (i.e. the final answer)
return mystack.top();
}
/*
BELOW ARE HELPER FUNCTIONS
*/
//Cleaning work on the expressions
string lineOperation(string afterEquals){
afterEquals = ReplaceString(afterEquals,";",""); //get rid of ;
afterEquals = ReplaceString(afterEquals," ",""); //get rid of space
afterEquals = ReplaceString(afterEquals,"++","!"); //replace ++ with !
afterEquals = ReplaceString(afterEquals,"--","@"); //replace -- with @ 5+++4
afterEquals = ReplaceString(afterEquals,"**","#"); //replace ** with #
afterEquals = ReplaceString(afterEquals,"mod","$"); //replace mod with $
return afterEquals;
}
//Sanity check function using stack
bool areParanthesisBalanced(string expr) {
stack <char> s;
char x;
// Traversing the Expression
for (int i=0; i<expr.length(); i++) {
if (expr[i]=='(') { //If the current character is a starting bracket
s.push(expr[i]); //push it to stack
}
//If the current character is a closing bracket
else if (expr[i]==')'){
if (s.top() == '(') s.pop();//pop from stack and check if it is the starting bracket
else return false;
}
}
//Balanced if no starting bracket left
return (s.empty());
}
bool isVariablePresent(string value){
for (int i = 0; i < value.size(); i++) { //iterate over ever character of input string
if(isalpha(value[i])) { //if a letter is found
return true;
}
}
return false;
}
bool isOperatorPresent(string value){
for (int i = 0; i < value.size(); i++) { //iterate over ever character of input string
if(isoperator(value[i])) { //if a letter is found
return true;
}
}
return false;
}
//String replacement
string ReplaceString(string subject, const string& search, const string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
bool isoperator(char ch){
if( ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='%'|| ch=='!'|| ch=='@'|| ch=='#'|| ch=='$')
return true;
else
return false;
}
bool isoperator(string str){
if( str=="+" || str=="-" || str=="*" || str=="/" || str=="%"|| str=="!"|| str=="@"|| str=="#"|| str=="$"|| str=="^")
return true;
else
return false;
}
vector<string> tokenize(string x){
vector <string> y;
//cout << "start of tokenization" << x << endl;
//cout<< "size of string for tokenization: "<<x.size()<<endl;
int i=0;
while(i<x.size()){
if(i == 0 and x[i] == '-' and (isdigit(x[i+1]) or x[i+1]=='(') ){//unary minus
//cout << i << " unary minus " << x[i] << endl;
y.push_back("^");
i++;
}
if (x[i] == '-' and (isdigit(x[i+1]) or x[i+1]=='(') and (not isdigit(x[i-1])) and x[i-1]!=')' ){ //(4-2)-(-1)
//cout << i << " unary minus " << x[i] << endl;
y.push_back("^");
i++;
}
else if (isdigit(x[i])){//add digits to number
string number;
while (isdigit(x[i]) or x[i] == '.' ) {
number += x[i];
i++;
}
// cout<<"FULL NUMBER IS--"<<number<<"--"<<endl;
//cout << "number is " << number << endl;
y.push_back(number);
}
else if (isalpha(x[i])){//add letters to variable
string variable;
while (isalpha(x[i])){
variable += x[i];
i++;
}
//cout << "variable is " << variable << endl;
y.push_back(variable);
}
else {// (, ), binary operators
//cout << "binary operator" << x[i] << endl;
//cout<<"PUSHING: --"<< x[i] << "--" << endl;
y.push_back(string(1, x[i]));
i++;
}
}
for(int i=0; i<y.size(); i++){
//cout << y[i] << " ";
}
//cout << endl;
return y;
}
vector<string> infix2postfix(vector<string> &x){
stack <string> mystack;
vector<string> y;
//cout << "post fix begins" << endl;
//1. Push “(“onto Stack, and add “)” to the end of X.
x.push_back(")");
mystack.push("(");
//2. Scan X from left to right and repeat Step 3 to 6 for each element of X
//until the Stack is empty.
int i=0;
while(!mystack.empty())
{
string str = x[i++];
//3. If an operand is encountered, add it to Y.
if (not isoperator(str) and str!="(" and str!=")"){
//cout << "push operand to vector: " << str << endl;
y.push_back(str);
}
//4. If a left parenthesis is encountered, push it onto Stack.
else if(str=="("){
//cout << "push ( to vector: " << str << endl;
mystack.push(str);
}
//5. If an operator is encountered, then:
else if(isoperator(str))
{ //a. 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 (isoperator(mystack.top()) and isleq(str,mystack.top()))
{
//cout << "push operator to vector: " << mystack.top() << endl;
y.push_back(mystack.top());
mystack.pop();
}
//b. Add operator to Stack.
mystack.push(str);
}
//.6. If a right parenthesis is encountered, then:
else if(str==")")
{
//a. Repeatedly pop from Stack and add to Y each operator
//(on the top of Stack) until a left parenthesis is encountered.
while(mystack.top()!="(")
{
//cout << "push ) to vector: " << mystack.top() << endl;
y.push_back(mystack.top());
mystack.pop();
}
//b. Remove the left Parenthesis.
mystack.pop();
}
}
// cout << "in post fix" << endl;
for (int i=0; i<y.size(); i++){
// cout << y[i] << " ";
}
//cout << endl;
return y;
}
bool isleq(string opA, string opB){
return (convertOpToInt(opA)<=convertOpToInt(opB));
}
int convertOpToInt (string str){
if (str=="+" || str=="-") return 1;
if (str=="*" || str=="/" || str=="%"|| str=="$") return 2;
if (str=="^" || str=="!"|| str=="#"|| str=="@") return 3;
return 0;
}