Rover class on a wrapping grid with obstacles and a trail
A warehouse robot drives on a rectangular floor grid. The floor wraps around: driving off the east edge brings the robot back in on the west edge, and the same for north and south. Some cells hold shelves the robot cannot enter. Implement a GridRover class that tracks the robot’s position, heading, and path.
(x, y) with 0 <= x < width and 0 <= y < height. (0, 0) is the bottom-left cell.'N', 'E', 'S', 'W'. Moving north adds 1 to y, east adds 1 to x, south subtracts 1 from y, west subtracts 1 from x.x = width - 1 heading east you arrive at x = 0.const rover = new GridRover({ width, height, obstacles?, start? });
// obstacles: Array<[x, y]> (default [])
// start: { x, y, heading } (default { x: 0, y: 0, heading: 'N' })
rover.forward(steps?) // => rover steps defaults to 1
rover.backward(steps?) // => rover moves opposite to the heading, without turning
rover.left() // => rover turns 90° counterclockwise (N → W)
rover.right() // => rover turns 90° clockwise (N → E)
rover.run(commands) // => rover e.g. 'FFRBL'
rover.position() // => { x, y, heading }
rover.blockedBy() // => { x, y } | null
rover.trail() // => Array<[x, y]>
position, blockedBy, and trail returns the rover, so calls can be chained.blockedBy() returns the obstacle’s cell.run(commands) runs the characters F (one step forward), B (one step back), L, and R in order. It stops at the first blocked step and skips the remaining commands. An empty string does nothing.forward, backward, left, right, or run first resets blockedBy() to null.trail() returns a new array of every cell the rover has been in, in order, starting with the start cell. Each step adds one entry. Turns and blocked steps add nothing.RangeError when:
width or height is not a positive integer;steps is not a non-negative integer;commands contains any character other than F, B, L, R (uppercase). Validate the whole string before running any of it.// 5 wide, 4 tall, one shelf at (2, 2)
const rover = new GridRover({ width: 5, height: 4, obstacles: [[2, 2]] });
rover.forward(2).right().forward(3);
rover.position(); // => { x: 1, y: 2, heading: 'E' } (stopped next to the shelf)
rover.blockedBy(); // => { x: 2, y: 2 }
rover.trail(); // => [[0, 0], [0, 1], [0, 2], [1, 2]]
rover.left().forward(2);
rover.position(); // => { x: 1, y: 0, heading: 'N' } (wrapped from y = 3 to y = 0)
rover.blockedBy(); // => null
rover.run('LF');
rover.position(); // => { x: 0, y: 0, heading: 'W' }
rover.run('F');
rover.position(); // => { x: 4, y: 0, heading: 'W' } (wrapped from x = 0 to x = 4)
rover.run('FX'); // throws RangeError, and the rover does not move