Skip to content

Instantly share code, notes, and snippets.

@ar1a
Last active May 1, 2016 08:24
Show Gist options
  • Save ar1a/af4c99462af38ec94782bace36a8b947 to your computer and use it in GitHub Desktop.
Save ar1a/af4c99462af38ec94782bace36a8b947 to your computer and use it in GitHub Desktop.
A command line calculator that uses the Shunting-Yard algorithm.
/*
Copyright (c) 2016 Snorflake
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream> //printf
#include <list> //std::list
#include <map> //std::map
#include <regex>
#include <sstream> //std::stringstream
#include <stack> //std::stack
#include <string> //std::getline std::string
#include <vector> //std::vector
enum class ASSOC { LEFT_ASSOC, RIGHT_ASSOC };
struct Opers {
Opers(ASSOC assoc, int priority) : assoc(assoc), priority(priority) {}
ASSOC assoc;
int priority; // higher == higher priority
};
class Calc
{
public:
/**
* Initilizes the calc class
* @param str Line of maths to evaluate
*/
Calc(const std::string& str) : str(str)
{
// Add operators here
assoc.emplace("+", Opers(ASSOC::LEFT_ASSOC, 0));
assoc.emplace("-", Opers(ASSOC::LEFT_ASSOC, 0));
assoc.emplace("*", Opers(ASSOC::LEFT_ASSOC, 1));
assoc.emplace("/", Opers(ASSOC::LEFT_ASSOC, 1));
assoc.emplace("^", Opers(ASSOC::RIGHT_ASSOC, 2));
assoc.emplace("%", Opers(ASSOC::RIGHT_ASSOC, 2));
}
/**
* Processes input and returns the equation in RPN
* @return RPN equation
*/
std::vector<std::string> process() const
{
if (str.empty()) {
throw std::runtime_error("input is empty!\n");
}
// Shunting yard algorithm
std::list<std::string> out;
std::stack<std::string> stack;
for (auto&& tok : tokenize()) {
if (tok.empty()) {
continue;
// this is a parsing error, ignore it
}
if (is_operator(tok)) {
while (!stack.empty() && is_operator(stack.top())) {
if ((get_assoc(tok) == ASSOC::LEFT_ASSOC &&
precedence_of(tok) <= precedence_of(stack.top())) ||
(get_assoc(tok) == ASSOC::RIGHT_ASSOC &&
precedence_of(tok) < precedence_of(stack.top()))) {
out.push_back(stack.top());
stack.pop();
if (stack.empty()) {
break;
}
} else {
break;
}
}
stack.push(tok);
} else if (tok == "(") {
// if its a bracket put it on the stack
stack.push(tok);
} else if (tok == ")") {
// end this equation so lets put the stuff on and discard the bracket
while (!stack.empty() && stack.top() != "(") {
out.push_back(stack.top());
stack.pop();
}
// this means that the user entered ( ... )) or some variation
if (stack.empty()) {
throw std::runtime_error("mismatched brackets!\n");
}
stack.pop();
} else if (isdigit(tok[0]) || tok[0] == '-') {
// we check if the first char is "-" so we can work with unary minus'
out.push_back(tok);
} else {
// user did something wrong so here we go
throw std::runtime_error("invalid operator!\n");
}
}
while (!stack.empty()) {
// if theres still stuff left on it just put it onto the output
out.push_back(stack.top());
stack.pop();
}
// this code moves the items from the std::list into the std::vector
std::vector<std::string> ret;
ret.assign(out.begin(), out.end());
return std::move(ret); // std::move hints to the compiler to use the move
// constructor instead of the copy constructor (more
// memory efficient)
}
/**
* Evaluates a RPN equation.
* @param tokens Tokens of the RPN equation.
* @return The answer to the equation.
*/
double convert(std::vector<std::string> tokens) const
{
std::stack<std::string> stack;
for (auto&& tok : tokens) {
// if it finds "(" or ")" it means process() didnt cut them out and the
// user entered something invalid
if (tok.find("(") != std::string::npos ||
tok.find(")") != std::string::npos) {
throw std::runtime_error("mismatched brackets!\n");
}
if (!is_operator(tok) && (isdigit(tok[0]) || tok[0] == '-')) {
// if its a number (even with a unary minus) then put it onto the stack
stack.push(tok);
} else { // its an operator so lets calculate things
double result = 0;
if (stack.empty()) {
throw std::runtime_error("invalid input!\n"); // user just hit enter
// so let's tell them
// they're stupid
}
// token is an operator so pop two entries
auto val2 = stack.top();
stack.pop();
auto&& d2 = strtod(val2.c_str(), 0);
if (!stack.empty()) {
// calc result
auto val1 = stack.top();
stack.pop();
auto&& d1 = strtod(val1.c_str(), 0);
if (tok.length() > 1) {
throw std::runtime_error("invalid token!\n"); // we should have
// thrown an error
// before here, but
// just in case
}
switch (tok[0]) {
case '+':
result = d1 + d2;
break;
case '-':
result = d1 - d2;
break;
case '/':
if (d2 == 0) {
throw std::runtime_error("division by zero!\n");
}
result = d1 / d2;
break;
case '*':
result = d1 * d2;
break;
case '^':
result = pow(d1, d2);
break;
case '%':
result = fmod(d1, d2);
break;
default:
throw std::runtime_error("invalid operator!\n");
}
// it didnt match anything we had so tell them they should enter
// something real
} else {
// handle unary operators
if (tok == "-") {
result = d2 * -1;
} else {
result = d2;
}
}
// this turns the double into a string!
std::stringstream ss;
ss << result;
stack.push(ss.str());
}
}
if (stack.empty()) {
throw std::runtime_error("invalid input!\n");
}
// converts the string to a double and returns it
char* err = nullptr;
auto retn = strtod(stack.top().c_str(), &err);
// triggered it user enters something like 6+9
// see: http://www.cplusplus.com/reference/cstdlib/strtod/
if (strlen(err) != 0) {
throw std::runtime_error("invalid input!\n");
}
return retn;
}
private:
/**
* Gets the priority of a token
* @param tok Token wanted
* @return Precedence of specified token
*/
int precedence_of(const std::string& tok) const
{
return assoc.find(tok)->second.priority;
}
/**
* Gets the side associaton of a token
* @param tok Token wanted
* @return Association of specified token
*/
ASSOC get_assoc(const std::string& tok) const
{
return assoc.find(tok)->second.assoc;
}
/**
* Returns if the token is an operator or not
* @param str Token wanted
* @return True if token is an operator
*/
bool is_operator(const std::string& str) const
{
return str == "+" || str == "-" || str == "/" || str == "*" || str == "^" ||
str == "%";
}
/**
* Tokenizes the expression, delimiing with a space
* @return An array of strings in order of input
*/
std::vector<std::string> tokenize() const
{
std::vector<std::string> ret;
std::regex reg(
"([ +\\-\\\\*\\/\\(\\)\\^%]|[^ +\\-\\\\*\\/\\(\\)\\^%]+)"); // holy
// shit
// rofl,
// see
// http://stackoverflow.com/a/27706957/4376737*/
std::sregex_iterator rit(str.begin(), str.end(), reg);
std::sregex_iterator rend;
while (rit != rend) {
if (rit->str() == " ") {
rit++;
continue;
}
ret.push_back(rit->str());
rit++;
}
return ret;
}
std::string str;
std::map<std::string, Opers> assoc;
};
int main()
{
printf("Supported operators: + - / * ^ %%\n");
// we need to do "%%" to print a literal %
while (1) {
std::string str;
printf("Input: ");
std::getline(
std::cin,
str); // gets the string from the command line when user hits enter
Calc calc(str); // initializes a calculator using specified equation from
// the user
try {
printf("%.5f\n", calc.convert(calc.process()));
} catch (std::exception& e) {
printf(e.what()); // If something threw an error then let's tell the
// user.
}
}
return 0; // return successful
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment