Task
Given an input, evaluate it as a mathematical equation following the order of operations.
But, instead of the using PEMDAS, we drop the parentheses and exponentiation and introduce spaces - SMDAS - spaces, then multiplication & division, then addition & subtraction.
How does that work?
Every operator with more spaces around it gets more precedence - but that can change from one side to the other. Usual precedence test - 2+2*2
still gets evaluated to 6 - so does 2 + 2*2
- which would be spelled out like two .. plus .. two-times-two
, but 2+2 *2
or 2+2 * 2
would equal 8 - twoPlusTwo .. times two
.
So, from any operator to any side every operator and number with less spaces can be grouped as in parentheses and then calculated as normal.
Alternatively, you can think of it as spaces around operators dropping the operator lower in precedence, or if the spaces are different on each side, drop the precedence on each side differently.
Examples
input = output
2+2*2 = 6
2+2-2 = 2
2+12/6 = 4
228+456/228 = 230
2+0*42 = 2
73-37-96+200 = 140
2+2 * 2 = 8
5*6 + 7*8 -3 *5 = 415
4+4*4+ 4*4-4*2 / 4*4-2 = 2
228+456 /228 = 3
2+2 * 3-6 * 4/2 + 4*3 + 1000 / 5*5 / 5-3 + 1 = 9
2+0 * 42 = 84
5*5 *7-1 = 174
Notes
- The input will always be valid - it will always contain at least 2 numbers, separated by a sign (
-+/*
(for which you may use alternatives such as∙
or÷
)) - The input will never end or start in spaces.
- There will never be unary subtraction -
-4*-6
. - There will never be division by zero.
- There may be negative integers in the process but never in the output.
- Division is only required to work for integers.
- Floating-point inaccuracies at any step of the process are fine.
- This is code-golf, shortest answer per language wins!
.0
okay? \$\endgroup\$.000001
as covered byFloating-point inaccuracies at any step of the process are fine
\$\endgroup\$