-
-
Save john01dav/937e20e0afee81a98eeb to your computer and use it in GitHub Desktop.
term.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <string> | |
#include <iostream> | |
#include "term.h" | |
using std::vector; | |
using std::string; | |
using std::stod; | |
using std::cout; | |
using std::endl; | |
vector<Term> parseEquation(string equationString){ | |
string::size_type location = 0; | |
vector<Term> equation; | |
while(true){ | |
Term term; | |
term.number = stod(equationString, &location); | |
if(location <= equationString.size()){ | |
term.operation = equationString[location]; | |
}else{ | |
term.operation = '\0'; | |
} | |
equation.push_back(term); | |
if(term.operation == '\0'){ | |
return equation; | |
}else{ | |
equationString = equationString.substr(location + 1); | |
} | |
} | |
} | |
void simplifyEquation(vector<Term> &equation){ | |
auto originalSize = equation.size(); | |
simplifyEquation(equation, '*'); if(equation.size() != originalSize) return; | |
simplifyEquation(equation, '/'); if(equation.size() != originalSize) return; | |
simplifyEquation(equation, '+'); if(equation.size() != originalSize) return; | |
simplifyEquation(equation, '-'); if(equation.size() != originalSize) return; | |
} | |
void simplifyEquation(vector<Term> &equation, const char &operation){ | |
vector<Term> result; | |
for(auto i=equation.begin();i != equation.end();i++){ | |
if(i->operation == operation){ | |
Term currentTerm = *i; | |
Term nextTerm = *(++i); | |
Term newTerm; | |
if(operation == '+'){ | |
newTerm.number = currentTerm.number + nextTerm.number; | |
}else if(operation == '-'){ | |
newTerm.number = currentTerm.number - nextTerm.number; | |
}else if(operation == '*'){ | |
newTerm.number = currentTerm.number * nextTerm.number; | |
}else if(operation == '/'){ | |
newTerm.number = currentTerm.number / nextTerm.number; | |
} | |
newTerm.operation = nextTerm.operation; | |
result.push_back(newTerm); | |
}else{ | |
result.push_back(*i); | |
} | |
} | |
equation = result; | |
} | |
void printEquation(const vector<Term> &equation){ | |
for(const Term &term : equation){ | |
cout << term.number; | |
if(term.operation == '\0'){ | |
return; | |
}else{ | |
cout << term.operation; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment