‹ back to the board

Wednesday, September 2

Apprenticelogic & control flow

The Lamplighter's Round of Gable Street

The lamplighter of bitwick walks Gable Street once a night, west to east, carrying a single can of oil.

You are given oil, a non-negative integer counting the measures of oil in the can at the start of the round, and posts, a list of integers describing what stands at each stop along the street, in the order the lamplighter reaches them.

Walk posts from first to last and treat each entry as follows:

  • A positive entry v is a lamp needing v measures of oil. If the can holds at least v, pour v out of the can and count the lamp as lit. If the can holds less than v, the round ends at once: every remaining entry of posts is ignored, including any barrels.
  • A negative entry v is a stashed barrel: add -v measures to the can. No lamp is lit.
  • A zero entry is an empty bracket: nothing changes.

Write lightLamps(oil, posts), which returns a list of exactly two integers: the number of lamps lit, and the measures of oil left in the can when the walk finished — either because the list ran out or because a lamp could not be filled.

  • loops with early exit
  • Apprentice

examples

  1. case 1oil of 5, posts of [2, 3, 4, 1][2, 0] — the 2-lamp and the 3-lamp empty the can, the 4-lamp cannot be filled, and the final 1-lamp is never reached
  2. case 2oil of 1, posts of [-4, 2, 0, 3][2, 0] — the barrel brings the can to 5, both lamps are lit, the bracket changes nothing
  3. case 3oil of 0, posts of [1, -10, 1][0, 0] — the first lamp needs 1 measure and the can is empty, so the barrel behind it is never opened
reward
210 XP
signature
lightLamps
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…
  • stops at the unaffordable lamp
  • barrels and brackets along the way
  • empty street
  • exact change for one lamp
  • barrel behind a failed lamp is never opened
  • nothing but barrels
  • full round with a late windfall
  • halts early with oil to spare
The Lamplighter's Round of Gable Street · bitwick