Simple Robot Simulation Algorithm


A Roomba robot is currently sitting in a Cartesian plane at (0, 0). You are given a list of its moves that it will make, containing NORTH, SOUTH, WEST, and EAST.

Return whether after its moves it will end up in the coordinate (x, y).

Constraints
n ≤ 100,000 where n is length of moves
Example 1
Input
moves = [“NORTH”, “EAST”]
x = 1
y = 1
Output
True
Explanation
Moving north moves it to (0, 1) and moving east moves it to (1, 1)

Example 2
Input
moves = [“WEST”, “EAST”]
x = 1
y = 0
Output
False
Explanation
This Roomba will end up at (0, 0)

Roomba Robot Algorithm

We can follow the instructions and update the current coordinate/position of the Roomba robot. The simulation algorithm is straightforward and takes O(N) time to complete.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool robotWalk(vector<string>& moves, int x, int y) {
    int cx = 0, cy = 0;
    for (auto &n: moves) {
        if (n == "NORTH") {
            cy ++;
        } else if (n == "EAST") {
            cx ++;
        } else if (n == "WEST") {
            cx --;
        } else if (n == "SOUTH") {
            cy --;
        }
    };
    return (cx == x) && (cy == y);
}
bool robotWalk(vector<string>& moves, int x, int y) {
    int cx = 0, cy = 0;
    for (auto &n: moves) {
        if (n == "NORTH") {
            cy ++;
        } else if (n == "EAST") {
            cx ++;
        } else if (n == "WEST") {
            cx --;
        } else if (n == "SOUTH") {
            cy --;
        }
    };
    return (cx == x) && (cy == y);
}

Python simulation for Robot:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def robotWalk(self, moves, x, y):
        cx = cy = 0
        for n in moves:
            if n == "SOUTH":
                cy -= 1
            elif n == "NORTH":
                cy += 1
            elif n == "WEST":
                cx -= 1
            elif n == "EAST":
                cx += 1
        return cx == x and cy == y
class Solution:
    def robotWalk(self, moves, x, y):
        cx = cy = 0
        for n in moves:
            if n == "SOUTH":
                cy -= 1
            elif n == "NORTH":
                cy += 1
            elif n == "WEST":
                cx -= 1
            elif n == "EAST":
                cx += 1
        return cx == x and cy == y

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
313 words
Last Post: Teaching Kids Programming - Depth First Search Algorithm to Sum the Root to Leaf Numbers in Binary Tree
Next Post: Teaching Kids Programming - Sibling Node in a Binary Search Tree

The Permanent URL is: Simple Robot Simulation Algorithm

Leave a Reply