‹ back to the board

today · Thursday, November 12

Apprenticelogic & control flow

The Hearth-Crystal of Skarnholt Glacier

The Skarnholt Glacier expedition is crossing the ice on foot, and its one defence against the cold is a hearth-crystal, a shard that stores warmth. The expedition's patron has posted this contract. Before the party sets out, tell them how many nights on their planned route will leave them frozen.

The crystal can hold at most cap units of warmth, and it starts the journey full, holding exactly cap.

The route is given as days, a list of integers, processed in order. Each entry changes the crystal as follows:

  • Positive value `d`: a sunlit day. The crystal gains d warmth, but it can never hold more than cap. Any excess is lost.
  • Zero: a calm day. Nothing changes.
  • Negative value `d`: a blizzard night that needs -d warmth.
  • If the crystal holds at least that much, the night is survived and the crystal loses exactly -d.
  • Otherwise the crystal is drained to 0 and the night counts as a frozen night.

Write frozenNights(cap, days).

  • cap is a non-negative integer.
  • days is a list of integers, possibly empty.

The function returns an integer: the number of frozen nights over the whole route.

  • running state across iterations
  • Apprentice

examples

  1. case 1cap of 5, days [-3, -3, 4, -5]2. Warmth goes 5 → 2, then frozen (drained to 0), then 4, then frozen again.
  2. case 2cap of 6, days [-2, 10, -6]0. Warmth goes 6 → 4, then the sun raises it only to the cap of 6, and the night needing exactly 6 is survived, leaving 0.
  3. case 3cap of 3, days []0
reward
210 XP
signature
frozenNights
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…
  • two frozen nights with recovery between
  • sunlight capped and exact need survived
  • empty route
  • zero capacity crystal
  • calm days change nothing
  • many small suns hit the cap
  • frozen while already empty
  • long drain of a large crystal
The Hearth-Crystal of Skarnholt Glacier · bitwick