Fix the poll schedule for a courier map
Your task
An AI kept a delivery map fresh by polling the courier's location every 200 ms in a while true loop. It never stopped, kept polling in the background, and drained the battery. The replacement uses a timer with separate foreground and background intervals, and cancels it when the map goes away. Your team checks the schedule it produces.
An assistant wrote plan_poll_times(state_changes, foreground_interval_ms, background_interval_ms, horizon_ms), the schedule. It is in the editor. It has a bug. Find it and fix it.
Input and output:
state_changes: the app's state over time, each writtenms:state, in increasing time order. The states areforeground,backgroundandstopped.foreground_interval_msandbackground_interval_ms: the polling interval in each state.horizon_ms: the last moment to plan for, included.- Return every time a poll request goes out, in increasing order.
Rules the tests check:
- Split a line at its first
:. Skip it unless the time is one or more digits from 0 to 9 and the state is one of the three above. - Each kept line starts a segment that lasts until the next kept line's time. The last segment runs past
horizon_ms. - In a foreground or background segment, a poll fires at the segment's start time and then once every interval, as long as the time is before the segment's end and not after
horizon_ms. - An interval of 0 or less means no polls in that state.
stoppedcancels the timer for good: no poll fires at or after it, even if a later line saysforegroundorbackground.
Examples
plan_poll_times(state_changes: list[str], foreground_interval_ms: int, background_interval_ms: int, horizon_ms: int) -> list[int]Example 1
Input
plan_poll_times(["0:foreground"], 200, 200, 1000)Output
[0, 200, 400, 600, 800, 1000]Example 2
Input
plan_poll_times(["0:foreground", "5000:background", "12000:foreground"], 2000, 0, 15000)Output
[0, 2000, 4000, 12000, 14000]Example 3
Input
plan_poll_times(["0:foreground", "3000:stopped"], 1000, 0, 10000)Output
[0, 1000, 2000]