Description Link to heading

2069. Walking Robot Simulation II (Medium)

Explanation Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East. robot.step(2); // It moves two steps East to (2, 0), and faces East. robot.step(2); // It moves two steps East to (4, 0), and faces East. robot.getPos(); // return [4, 0] robot.getDir(); // return "East" robot.step(2); // It moves one step East to (5, 0), and faces East. // Moving the next step East would be out of bounds, so it turns and faces North. // Then, it moves one step North to (5, 1), and faces North. robot.step(1); // It moves one step North to (5, 2), and faces North (not West). robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West. // Then, it moves four steps West to (1, 2), and faces West. robot.getPos(); // return [1, 2] robot.getDir(); // return "West"

Solution Link to heading

This is a somewhat tricky simulation problem, but it becomes straightforward when you notice two points:

  1. The robot will only be positioned on the outermost layer of the grid.
  2. We can keep track of the total number of steps the robot has moved. This way, we can calculate the paths starting from $(0, 0)$ without needing to use the robot’s previous position.

Code Link to heading

class Robot {
  public:
    Robot(int width, int height) {
        wid_ = width;
        hei_ = height;
    }

    void step(int num) {
        total += num;
        if (total == 0) {
            return;
        }
        int realmove = total % (wid_ - 1 + hei_ - 1 + wid_ - 1 + hei_ - 1);
        if (realmove == 0) {
            direct = 3;
            posx = 0;
            posy = 0;
        } else if (realmove > 0 && realmove <= wid_ - 1) {
            direct = 0;
            posx = realmove;
            posy = 0;
        } else if (realmove > wid_ - 1 && realmove <= wid_ - 1 + hei_ - 1) {
            posx = wid_ - 1;
            posy = realmove - (wid_ - 1);
            direct = 1;
        } else if (realmove > wid_ - 1 + hei_ - 1 && realmove <= wid_ - 1 + hei_ - 1 + wid_ - 1) {
            posy = hei_ - 1;
            posx = wid_ - 1 - (realmove - (wid_ - 1 + hei_ - 1));
            direct = 2;
        } else {
            posx = 0;
            posy = hei_ - 1 - (realmove - (wid_ - 1 + hei_ - 1 + wid_ - 1));
            direct = 3;
        }
    }

    vector<int> getPos() {
        return {posx, posy};
    }

    string getDir() {
        switch (direct % 4) {
        case 0:
            return "East";
        case 1:
            return "North";
        case 2:
            return "West";
        case 3:
            return "South";
        }
        return "";
    }

  private:
    int posx = 0;
    int posy = 0;
    int direct = 0;
    int wid_;
    int hei_;
    int total = 0;
};