Consider a finite, one-dimensional grid where each cell is marked with one of two symbols (I will use the symbols <
and >
, but you can use other symbols).
When a pinball is placed on one of the cells, it moves according to the following rules:
- If the pinball is on a cell that is marked with
<
, the pinball moves one cell left in the next second, and if marked with>
, it moves one cell right in the next second. - After the pinball has moved, the marker on the cell is inverted (i. e. if cell was marked with
<
, it becomes>
, and vice versa). - The pinball stops moving when it leaves the grid.
Challenge
Given the initial markers on the grid and a starting location for the pinball, calculate how many seconds it would take for the pinball to leave the grid.
Input Format
- You may represent the markers on the initial grid as an array/string containing two distinct values.
- You may take the starting position as a 0-indexed or 1-indexed value.
Worked example
initial grid = ><<, start = 1
* * * * * * *
><< >>< <>< <<< <<> <>> >>>
1 2 3 4 5 6
Here the *
represents the pinball, and the numbers on the bottom represent the time elapsed.
Testcases
><<, 0 -> 3
><<, 1 -> 6
><<, 2 -> 5
<<<<, 0 -> 1
<<<<, 3 -> 4
<><<<>, 1 -> 4
<><<<>, 3 -> 10
<><<<>, 4 -> 8
<><<<>, 5 -> 1
Based on this Codeforces problem (Same problem but you need to solve for all starting locations in linear time)