progress

~/problems / Simulation & OOP design / Simulation

Rain barrel log

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A cabin's rain barrel holds at most capacity litres and starts with start. rain[i] is the rain collected on day i + 1. Each day, in order:

  1. Rain: add the rain. Anything above capacity spills; add it to spilled.
  2. Use: draw use litres. If there's less than that, take what's there (level 0) and count a dry day. Taking exactly the last litre isn't dry.
  3. Clean: if the day number (1-based) is a multiple of clean_every, pour the rest away (not counted as spilled).

Write rain_barrel(capacity: int, start: int, use: int, clean_every: int, rain: list[int]) -> tuple[int, int, int] returning (level, spilled, dry_days) after 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

Up to 10^5 days; all amounts are non-negative.

Show hint

keep level, spilled and dry, apply the three steps each day, and use enumerate(rain, start=1) for the 1-based day number.

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

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc