Expert · Simulation · 258 of 264
Robot on a grid
A robot starts at (0, 0) facing north. Commands: L and R turn 90 degrees, F moves one step forward unless an obstacle is there (then it stays). North increases y, east increases x.
Input: the commands on one line, then k, then k obstacle lines "x y". Output: the final x y and direction (N, E, S or W).
Examples
Input
FFRFF 0
Output
2 2 E
Input
FFRFF 1 0 2
Output
2 1 E
Input
LLLL 0
Output
0 0 N
One more test checks other inputs when you press Check.
Stuck? The idea behind simulation
Follow the rules step by step, exactly as written: keep the state (a grid, a position), and work out the next state from the current one.
When every cell changes at once, build the new grid apart from the old one.
x, y = 0, 0
for move in "NNEES":
x += {"E": 1, "W": -1}.get(move, 0)
y += {"N": 1, "S": -1}.get(move, 0)
print(x, y)Watch for: Changing the grid while still reading it mixes this step with the next.