Apprenticelogic & control flow
The Lanternbearer of the Hollow Deep
The Delvers' Guild of Bitwick seeks a lanternbearer to lead an expedition into the Hollow Deep, a chain of lightless chambers beneath the old barrow. The expedition passes through the chambers strictly in order. It cannot move past a dark chamber unless the lantern has enough oil to cross it. The Guild wants to know, before anyone descends, how many chambers the party will get through.
Write lanternReach(oil, cap, rooms).
oilis a non-negative integer: the oil in the lantern at the start, with0 <= oil <= cap.capis a non-negative integer: the most oil the lantern can hold.roomsis a list of integers, one per chamber, in the order the party enters them.
Each chamber is handled as follows:
- Positive value `r`: the chamber holds an oil cache. The lantern gains
roil, but it can never hold more thancap. Any oil beyondcapis lost. The chamber is passed. - Zero: the chamber costs nothing and is passed.
- Negative value `-k`: the chamber is dark and crossing it costs
koil. - If the lantern holds at least
koil, the party spendskoil and passes the chamber. The lantern may be left with exactly 0 oil. - Otherwise the expedition halts at that chamber. It does not pass it, and it enters no later chambers.
Return an integer: the number of chambers the party passes. If every chamber is passed, this is the length of rooms. If rooms is empty, return 0.
examples
- case 1
oil of 8, cap of 10, rooms of [5, -10, -1]2. The cache would bring the lantern to 13, but it holds only 10. The second chamber spends all 10, and the third chamber cannot be crossed. - case 2
oil of 2, cap of 4, rooms of [0, -2, 3, 0, -3]5. The oil goes 2, 2, 0, 3, 3, 0, so every chamber is passed. - case 3
oil of 0, cap of 5, rooms of [-1, 5]0. The party halts at the first chamber and never reaches the cache beyond it.
- reward
- 220 XP
- signature
lanternReach
TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.
loading the editor…
- cache overflow is lost
- every chamber passed
- empty deep
- halts at first chamber
- exact oil suffices
- mixed descent halts midway
- repeated clamping
- long drain
- zero capacity with free chambers