Say I have an expression:
9 * 8 + 1 - 4
This expression can be interpreted in six different ways, depending on operator precedence:
(((9 * 8) + 1) - 4) = 69 (* + -)
((9 * 8) + (1 - 4)) = 69 (* - +)
((9 * (8 + 1)) - 4) = 77 (+ * -)
(9 * ((8 + 1) - 4)) = 45 (+ - *)
((9 * 8) + (1 - 4)) = 69 (- * +)
(9 * (8 + (1 - 4))) = 45 (- + *)
Say I'm a developer, and I don't feel like memorizing precedence tables, etc., so I'm just going to guess.
In this case, the largest margin of error would be 45-77, which is a difference of 32. This means that my guess will only be off by a maximum of 32.
The challenge
Given an expression consisting of numbers and +
, -
, *
, /
(integer division) and %
, output the absolute difference of the largest and smallest possible value for that expression, based on the precedence of operators.
Specifications
- The input expression will not contain parenthesis and every operator is left-associative.
- The input expression will only contain nonnegative integers. However, subexpressions may evaluate to negatives (e.g.
1 - 4
). - You can take the expression in any reasonable format. For example:
"9 * 8 + 1 - 4"
"9*8+1-4"
[9, "*", 8, "+", 1, "-", 4]
[9, 8, 1, 4], ["*", "+", "-"]
- The input will contain at least 1 and at most 10 operators.
- Any expression that contains a division or modulo by 0 should be ignored.
- You can assume that modulo will not be given negative operands.
Test Cases
9 * 8 + 1 - 4 32
1 + 3 * 4 3
1 + 1 0
8 - 6 + 1 * 0 8
60 / 8 % 8 * 6 % 4 * 5 63
%
as having two different precedences in your second example. \$\endgroup\$%
operator works on negative numbers? The way like C or Python or something else? \$\endgroup\$