‹ back to the board

Wednesday, September 30

Apprenticelogic & control flow

The Rain Barrel at the Watch-House

The watch-house on the north wall keeps one rain barrel, and the night warden keeps a strip of birch bark with the barrel's fortunes written on it in order.

Each mark on the bark is an integer:

  • a positive number is rain, adding that many pails to the barrel;
  • a negative number is the guards drawing water, taking that many pails out;
  • a zero is a quiet watch and changes nothing.

The barrel starts empty and holds at most cap pails. Rain that would carry the level above cap fills the barrel to the brim and the rest spills away. A draw that asks for more than the barrel holds empties it completely, and the pails that could not be given are unmet.

Write rainBarrel(entries, cap), where entries is a list of integers (possibly empty) read left to right and cap is an integer of at least 0. Return a list of exactly three integers: the barrel's final level, the total pails spilled over all entries, and the total pails left unmet over all entries.

  • accumulating over a sequence
  • Apprentice

examples

  1. case 1entries of [3, -1, 5, -10], cap of 6[0, 1, 4] — the barrel reaches 2, then rain of 5 fills it to 6 and spills 1; the final draw takes all 6 and leaves 4 unmet
  2. case 2entries of [5, -5], cap of 5[0, 0, 0] — filling exactly to the brim spills nothing, and a draw that empties it exactly leaves nothing unmet
  3. case 3entries of [4, -2], cap of 0[0, 4, 2] — a barrel with no room spills every pail of rain and can give nothing back
reward
200 XP
signature
rainBarrel
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…
  • a night of rain and thirst
  • blank bark
  • a barrel with no room
  • exactly to the brim
  • quiet watches change nothing
  • drawing from an empty barrel
  • one long downpour
The Rain Barrel at the Watch-House · bitwick