Posted on

Description

Submission

class Robot {
    int dir;
    int cycle;
    int x;
    int y;
    int width;
    int height;
    vector<pair<int, int>> dirs;
public:
    Robot(int width, int height) 
        :
        dir(0),
        cycle(2 * (width + height - 2)),
        x(0),
        y(0),
        width(width),
        height(height)
    {
        // 0, 1, 2, 3
        dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    }
    
    void step(int num) {
        while(num > 0) {
            int remain = 0;
            if(dir == 0) remain = width - 1 - x;
            else if(dir == 1) remain = height - 1 - y;
            else if(dir == 2) remain = x;
            else if(dir == 3) remain = y;
            
            if(remain >= num) {
                x += dirs[dir].first * num;
                y += dirs[dir].second * num;
                num = 0;
            } else {
                x += dirs[dir].first * remain;
                y += dirs[dir].second * remain;
                num -= remain;
                dir = (dir+1)%4;

                num %= cycle;
                if(num == 0 && ((x == 0 && y == 0) || (x == 0 && y == height - 1) ||
                 (x == width - 1 && y == height -1) || (x == width - 1 && y == 0))) {
                    dir = (dir+3) % 4;
                }
            }
        }
        
    }
    
    vector<int> getPos() {
        return {x, y};
    }
    
    string getDir() {
        switch(dir) {
            case 0: return "East";
            case 1: return "North";
            case 2: return "West";
            case 3: return "South";
        }
        return "";
    }
};

/**
 * Your Robot object will be instantiated and called as such:
 * Robot* obj = new Robot(width, height);
 * obj->step(num);
 * vector<int> param_2 = obj->getPos();
 * string param_3 = obj->getDir();
 */

Leave a Reply

Your email address will not be published. Required fields are marked *