re
run
.
me

Evaluating Infix Expression - Multiple Digits

If you are looking for evaluating an infix expression with parantheses, don’t waste your time here. Visit my other fresh write up here

Infix1 Infix2 Infix3

These images have been running around Facebook for a while now. Though it is eye-damaging primary level arithmetic, it is kind of sweet to write it as a program. Just for the fun of it, I created an html page driven by a javascript implementation. Here is the link.

So, essentially the idea is to evaluate the infix notation in a natural way - respecting the operator precedence. (If you consider this as a puzzle, then there are other variations which involves evaluating the expression in such a way that the result is a maximum value/minimum value)

Please note that the algorithm (and therefore, the program), as it stands does not handle parentheses. This is just a two-stack algorithm with a small variation to accommodate numbers more than a digit.

The algorithm goes like this :

1. Initialize two stacks - one for holding values and one for holding operators
2. Read the input expression from left to right - one character at a time. 
3. If the character is a space, ignore
4. If the character is a number, then append it to an accumulating variable 
   (don't push it to the stack yet) 
5. If the character is an operator, push the accumulated number to the value stack and 
   reinitialize the accumulator.

    5a. If the current operator is of higher precedence than the first item in the operator stack,
        then safely ignore and read further.

    5b. If the current operator is of lower precedence than the first item in the operator 
        stack (peek view), then evaluate the previous set (two from value stack and one 
        from operator stack) and insert the result into the value stack

    5c. Finally, insert the current operator to the operator stack

A Groovy implementation is here :

Comments