One of my favorite exercises that i’ve mentored a lot in the past. In addition to the story, the description has also received a facelift.
Introduction
The testing floor in the robot factory was quiet, filled only with the soft hum of machinery. You stand by, watching as your robot, the result of months of hard work, is placed on the grid. It isn’t just the robot being tested, but the program you are writing to control its movements. Your program will guide the robot through a series of instructions, and the testing facility will verify whether the robot ends up in the correct position and facing the right direction.
The robot stands at a random position, waiting for its next set of commands. With each instruction, it will move, turn, or advance on the grid. Will it follow the commands correctly? The test facility will soon provide the answer.
Instructions
Write a robot simulator.
The task is to simulate the movement of a robot on a hypothetical infinite grid, where the robot can perform three actions:
- turn right
- turn left
- advance forward one unit
The robot starts at a specific set of coordinates {x, y} (e.g., {3, 8}), facing one of four possible directions: north, east, south, or west. The x
part of the coordinates increases when moving east, and the y
part increases when moving north.
The robot will receive a sequence of instructions consisting of the letters “R”, “L”, and “A”, each representing one of the three actions. After executing all the instructions the testing facility verifies the robot’s new position, and in which direction it is facing.
Example
A robot starts at {7, 3} facing north and executes the instructions “RAALAL”:
- R: Turns right and is now facing east.
- A: Advances to {8, 3}.
- A: Advances to {9, 3}.
- L: Turns left and is now facing north.
- A: Advances to {9, 4}.
- L: Turns left again and is now facing west.
The robot’s final coordinates are {9, 4}, and it is facing west.