~/problems / Simulation & OOP design / Simulation

Rain barrel log

easy ~15 min

A cabin gets its water from a rain barrel that holds at most capacity litres and starts the season holding start litres. rain[i] is the rainfall (in litres collected) on day i + 1. Every day, in this exact order:

  1. Rain: add that day's rain. Anything above capacity spills over the top; add the spilled amount to the season's spilled total.
  2. Use: the cabin draws use litres. If the barrel holds less than that, they take whatever is there (the barrel goes to 0) and the day counts as a dry day. Drawing exactly the last litre is not a dry day.
  3. Clean: if the day number (1-based) is a multiple of clean_every, the barrel is scrubbed and whatever is left is poured away. Poured-away water is not counted as spilled.

Write rain_barrel(capacity: int, start: int, use: int, clean_every: int, rain: list[int]) -> tuple[int, int, int] that returns (level, spilled, dry_days) at the end of the last day.

rain_barrel(10, 4, 3, 3, [5, 8, 0, 2])   # (0, 4, 1)
# day 1: 4+5=9, use -> 6
# day 2: 6+8=14 -> 10, spilled 4; use -> 7
# day 3: 7+0=7, use -> 4; day 3 is a cleaning day -> 0
# day 4: 0+2=2, use needs 3 -> dry day, level 0

rain_barrel(5, 5, 1, 100, [])            # (5, 0, 0)   no days at all
  • 1 <= capacity <= 10^6; 0 <= start <= capacity; 0 <= use <= 10^6; 1 <= clean_every <= 10^6; 0 <= len(rain) <= 10^5; each rain[i] is in [0, 10^6].
Show hint

keep three variables (level, spilled, dry) and apply the three steps to them in order for each day; use enumerate(rain, start=1) so the day number for the cleaning check is 1-based.

Topic: Simulation. Model the process exactly; watch simultaneous updates and direction arithmetic.

0:00
Ctrl ' run · Ctrl ↵ submit
esc