progress

~/problems / Coordination / Barrier

Street lamps that copy their neighbours

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

Each night, every smart lamp on a street picks a new brightness with rule(left, mine, right), using its own and its neighbours' values from the previous night (end lamps see 0 for the missing one). The controllers are slow, so run one thread per lamp, in parallel.

Implement simulate(start: list[int], nights: int, rule) -> list[int]: lamp i's thread makes all of lamp i's rule calls, one per night, and you return the brightnesses after nights nights. A lamp must never see a value a faster neighbour already computed for the current night.

spread = lambda l, m, r: max(l, m, r)
simulate([0, 0, 5, 0, 0], 1, spread)   # [0, 5, 5, 5, 0]
simulate([0, 0, 5, 0, 0], 2, spread)   # [5, 5, 5, 5, 5]
simulate([3, 1], 0, spread)            # [3, 1]   no nights, no rule calls

The bug the tests hunt: night 1 above becoming [0, 5, 5, 5, 5] because lamp 3 already shows 5 when lamp 4 looks.

Up to 20 lamps and 50 nights; rule takes varying time. Don't sleep or busy-wait. start may be empty: then return [].

Show hint

keep "current" and a separate "next" list; each thread writes only its own slot, then meets the others at threading.Barrier(len(start), action=...). The action runs once, after all have written and before any is released: swap the lists there. A Barrier needs at least 1 party, so handle the empty street first.

Topic: Barrier. Rendezvous: n threads wait until all arrive.

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