We all know the standard order of operations for math functions (PEMDAS), but what if we instead evaluated expressions left-to-right?
The Challenge
Given a string through standard input or through command line args, find the difference between the traditional evaluation (PEMDAS) and the in-order (left-to-right) evaluation of that expression.
Details
You will be given a string in a format such as:
"1 + 2 * 3 ^ 2 - 11 / 2 + 16"
To simplify things, there will be:
- a space between each number and operator
- no leading or trailing spaces
- no decimal numbers or negative numbers (non-negative integers only)
- no operators beyond +(plus), -(minus), *(multiply), /(divide), ^(exponentiation)
- no parens to worry about
- you may remove the spaces if it's easier for you to handle, but no other modification of the input format will be allowed.
You must provide the absolute value of the difference between the two evaluations of the string
- Your division can either be floating-point or integer division - both will be accepted
Your program can not use any sort of expression evaluation library.
To clarify - any sort of built-in eval function in which your language evaluates a string that is valid code for the same language IS acceptable
- Explanations of your code are preferred
- Shortest code by byte count wins
- Winner will be chosen Saturday (July 19, 2014)
Examples:
A: 1 + 2 * 3 ^ 2 - 11 / 2 + 16 (using floating-point division)
In traditional order of operations:
1 + 2 * 3 ^ 2 - 11 / 2 + 16 --> 1 + 2 * 9 - 11 / 2 + 16 --> 1 + 18 - 5.5 + 16 --> 29.5
In-order traversal yields:
1 + 2 * 3 ^ 2 - 11 / 2 + 16 --> 3 * 3 ^ 2 - 11 / 2 + 16 --> 9 ^ 2 - 11 / 2 + 16 --> 81 - 11 / 2 + 16 --> 70 / 2 + 16 --> 35 + 16 --> 51
Resulting difference: 51 - 29.5 = 21.5
B: 7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 (using integer division)
In traditional order of operations:
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 7 - 1 * 9 + 41 / 3 + 2 * 9 * 2 --> 7 - 9 + 13 + 18 * 2 --> 7 - 9 + 13 + 36 --> 47
In-order traversal yields:
7 - 1 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 6 * 3 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 18 ^ 2 + 41 / 3 + 2 * 9 * 2 --> 324 + 41 / 3 + 2 * 9 * 2 --> 365 / 3 + 2 * 9 * 2 --> 121 + 2 * 9 * 2 --> 123 * 9 * 2 --> 1107 * 2 --> 2214
Resulting difference: 2214 - 47 = 2167
eval
forbidden? If so It appears that only the Haskell answer is valid. \$\endgroup\$eval
sort of vastly simplify the challenge? I mean for most langauges with eval, eval = the traditional order. (And surely you folks can do better than Haskell, even withouteval
...!) \$\endgroup\$