The Toll-Stone of Blackreed Bridge
The toll-keeper at Blackreed Bridge does not name a price. He carves each traveller's toll onto a stone as an inscription, and the count house has a winter's worth of stones still to tot up.
An inscription is a string. Its tokens are runs of decimal digits (never signed), the operators ? + - * / % ^, the round marks ( ), and the squared marks [ ]. Whitespace may appear between tokens and means nothing. Every inscription you are given is well-formed.
Given expr, a string, return the inscription's value as an integer — or the null value of your language (null in TypeScript, None in Python) in the single case described at the end.
Binding, loosest first:
1. ? — binary, right-associative (loosest) 2. + - — binary, left-associative 3. * / % — binary, left-associative 4. - — unary prefix, may be repeated 5. ^ — binary, right-associative (tightest)
Meanings:
a ? b— the value ofa, if that value is not 0; otherwise the value ofb. When the value ofais not 0,bis never evaluated at all.+-(binary)*— ordinary integer addition, subtraction, multiplication./— integer division truncating toward zero (so-7 / 2is-3, not-4).%— the remainder left by that same truncating division:a % bequalsa - (a / b) * b, so its sign followsa.-(unary) — negation.^— exponentiation. Every exponent is a non-negative integer, and-never appears immediately after^.0 ^ 0is1.( e )is the value ofe;[ e ]is the absolute value ofe. Either may contain any inscription.
The null case: if a / or a % is evaluated with a right-hand value of 0, the inscription has no value and you return null. A subexpression that is never evaluated cannot cause this.
All intermediate and final values fit in the range ±2^53.
examples
- case 1
expr of "-3 ^ 2 + [4 - 9]"-4 — the power binds tighter than the negation, so the first term is -9, and the squared marks give 5 - case 2
expr of "5 ? 7 / 0"5 — the left value is not 0, so the right side is never evaluated and the zero divisor never happens - case 3
expr of "0 ? 7 / 0"null (None in Python) — here the right side is evaluated, and it divides by zero - case 4
expr of "(-7 / 2) * 10 + -7 % 2"-31 — -7 / 2 truncates to -3, giving -30, and -7 % 2 is -1
- reward
- 540 XP
- signature
tollValue
TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.
- power tower binds rightward
- negation sits below the power, with squared marks
- fallback skips a zero divisor
- fallback takes the branch that divides by zero
- zero divisor on the evaluated left side
- truncating division and signed remainder
- fallback is right-associative and loosest
- second fallback rescues the buried divisor
- nested squared marks raised to a power
- negation between product and power
- stacked negations against an absolute value
- grouped fallback added to a power
- remainder with a negative divisor
- lone number padded with whitespace
- zero to the zero