‹ back to the board

Tuesday, October 27

Apprenticelogic & control flow

The Lantern-Oil of Cresswake Grotto

The smugglers' caves beneath Cresswake Isle run deep, and a boat that loses its light in there does not come back out. The Tidewardens of Cresswake will pay any crew that charts the grottoes ahead of time. To earn the bounty, a crew must say exactly where a lantern would go dark.

The crew's lantern starts with oil measures of oil and can hold at most cap measures. The boat passes through the grottoes in order. Each grotto is one integer in the list grottoes:

  • A negative value is oil burned while crossing that grotto.
  • A positive value is oil taken from a smugglers' cache there.
  • Zero leaves the lantern unchanged.

For each grotto in turn, add its value to the current oil, then apply these rules:

  • If the oil is now below zero, the crew is stranded in that grotto.
  • If the oil is now above cap, it is reduced to exactly cap. The overflow is spilled and lost.
  • Oil of exactly zero is not stranded, and the crew continues.

Write strandedAt(oil, cap, grottoes). It returns the 0-based index of the first grotto where the crew is stranded, or -1 if the crew passes through every grotto without being stranded.

All arguments are integers, and grottoes is a list of integers that may be empty. You may assume 0 <= oil <= cap.

  • loops with early exit
  • Apprentice

examples

  1. case 1oil of 4, cap of 5, grottoes [6, -3, -3]2 — the cache would bring the lantern to 10, but it holds only 5, so the oil goes 5, then 2, then -1
  2. case 2oil of 3, cap of 3, grottoes [-1, -2]-1 — the oil goes to 2, then exactly 0, which is still lit
  3. case 3oil of 0, cap of 0, grottoes []-1 — there are no grottoes to cross
reward
210 XP
signature
strandedAt
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…
  • burns out on third grotto
  • cap spills cache oil
  • exactly zero survives
  • empty grottoes
  • stranded in first grotto
  • long route with repeated spilling
  • zero capacity lantern
  • passes through all