~/problems / Simulation & OOP design / Simulation

Basics: robot on a walled grid (state + step loop)

easy basics ~10 min

A robot stands in a room of width × height cells. Cells are (x, y) with 0 <= x < width and 0 <= y < height. The robot starts 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 in order and returns the final (x, y, facing), where facing is one of "N", "E", "S", "W":

  • "L": turn 90° left, staying on the same cell.
  • "R": turn 90° right, staying on the same cell.
  • "F": move one cell forward. If that cell would be outside the room, the robot bumps the wall and stays where it is (it keeps its facing).
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; 0 <= len(commands) <= 10^4; commands only contain L, R, F.
Show hint

keep the directions in clockwise order, [(0, 1), (1, 0), (0, -1), (-1, 0)] for N, E, S, W; a right turn is d = (d + 1) % 4, a left turn is d = (d + 3) % 4, and you compute the next cell first and only move if it's inside the room.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc