progress

~/problems / Simulation & OOP design / Simulation

Robot on a walled grid

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

easy basics ~10 min

A robot sits in a width × height room of cells (x, y), starting at (0, 0) facing north (north is y + 1, east is x + 1).

Write walk(width: int, height: int, commands: str) -> tuple[int, int, str] that runs the commands and returns the final (x, y, facing), with facing one of "N", "E", "S", "W":

  • "L" / "R": turn 90° left / right on the spot.
  • "F": step forward one cell, unless that cell is outside the room: then the robot stays put.
walk(3, 3, "FFRFF")    # (2, 2, "E")
walk(3, 3, "FFFFF")    # (0, 2, "N")   bumps the north wall three times
walk(2, 2, "L")        # (0, 0, "W")

1 <= width, height <= 100; up to 10^4 commands.

Show hint

keep the directions clockwise, [(0, 1), (1, 0), (0, -1), (-1, 0)]; a right turn is d = (d + 1) % 4, a left turn d = (d + 3) % 4. Compute the next cell first and move only if it's inside.

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

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