#include <queue>
#include <stack>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include "evaluator.h"
using std::queue;
using std::stack;
using namespace std;
queue<Token> infixToPostfix(queue<Token> infixExpression){
queue<Token> postfixExpression;
stack<Token> stackTemp;
while( !infixExpression.empty() )
{
if( giveType(infixExpression.front()) == "(" )
{
stackTemp.push(infixExpression.front());
}
if( giveType(infixExpression.front()) == "number")
{
postfixExpression.push(infixExpression.front());
}
if( giveType(infixExpression.front()) == "symb")
{
while(!stackTemp.empty())
{
if( isGreater(stackTemp.top(), infixExpression.front()))
{
if( giveType(stackTemp.top()) != "(" )
{
postfixExpression.push(stackTemp.top());
}
break;
}
else
break;
}
stackTemp.push(infixExpression.front());
}
if( giveType(infixExpression.front()) == ")")
{
while( !stackTemp.empty() && giveType(stackTemp.top())!= "(" )
{
postfixExpression.push(stackTemp.top());
stackTemp.pop();
}
if( !stackTemp.empty())
{
stackTemp.pop();
}
else
throw string("unbalanced");
}
infixExpression.pop();
}
while(!stackTemp.empty())
{
postfixExpression.push(stackTemp.top());
stackTemp.pop();
}
return postfixExpression;
}
// returns postfix translation of infix expression parameter
bool isGreater(Token first, Token second){
if( (getVal(first)) > (getVal(second)))
{
return true;
}
else
return false;
}
int getVal(Token t){
int value;
if(t.op() == add || t.op() == subtract)
{
value = 1;
}
if(t.op() == multiply || t.op() == divide)
{
value = 2;
}
if(t.op() == power)
{
value = 3;
}
return value;
}
string giveType(Token t){
if(t.isNumber())
{
return "number";
}
if(t.op() == leftParen)
{
return "(";
}
if(t.op() == rightParen)
{
return ")";
}
else
return "symb";
}
double evaluatePostfix(queue<Token> expression)
{
double result,temp,temp2;
stack<double> stackTemp;
while(!expression.empty())
{
if( expression.front().isNumber())
{
stackTemp.push(expression.front().value());
expression.pop();
}
else
if( !stackTemp.empty())
{
temp = stackTemp.top();
stackTemp.pop();
}
else
throw string("bad expression");
if( !stackTemp.empty())
{
temp2 = stackTemp.top();
stackTemp.pop();
}
else
throw string("bad expression");
if( expression.front().op() == add)
{
stackTemp.push((double)(temp + temp2));
}
else
if( expression.front().op() == subtract)
{
stackTemp.push((double)(temp2 - temp));
}
else
if(expression.front().op() == multiply)
{
stackTemp.push((double)(temp * temp2));
}
else
if(expression.front().op() == divide)
{
if(temp == 0)
{
throw string("divide by zero");
}
else
stackTemp.push((double)(temp2 / temp));
}
else
if(expression.front().op() == power)
{
stackTemp.push( (double).pow(temp2,temp)));
}
expression.pop();
}
result = (double)stackTemp.top();
stackTemp.pop();
if(!stackTemp.empty())
{
if(stackTemp.top()!=0)
{
throw string("bad expression");
}
return result;
}
}