‹ back to the board

Friday, October 2

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).

  • oil is a non-negative integer: the oil in the lantern at the start, with 0 <= oil <= cap.
  • cap is a non-negative integer: the most oil the lantern can hold.
  • rooms is 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 r oil, but it can never hold more than cap. Any oil beyond cap is lost. The chamber is passed.
  • Zero: the chamber costs nothing and is passed.
  • Negative value `-k`: the chamber is dark and crossing it costs k oil.
  • If the lantern holds at least k oil, the party spends k oil 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.

  • running state across iterations
  • Apprentice

examples

  1. case 1oil 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.
  2. case 2oil 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.
  3. case 3oil 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
not yet run

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
The Lanternbearer of the Hollow Deep · bitwick