2025-08-21 09:41:54 +0000 UTC

Walking Robot Simulation II

Code

class Robot:

    def __init__(self, width: int, height: int):
        self.cur = (0, 0)
        self.cur_dir = 0
        self.width = width
        self.height = height
        self.dir_mapping = {
            0: "East",
            1: "North",
            2: "West",
            3: "South"
        }
        self.mod = 2 * (self.width + self.height - 2)

    def step(self, num: int) -> None:
        if num >= self.mod:
            num %= self.mod
            if self.cur == (0, 0) and self.cur_dir == 0:
                self.cur_dir = 3
        row, col = self.cur
        while num > 0:
            if self.cur_dir == 0:
                steps = min(num, self.width - row -1)
                num -= steps
                row += steps
            elif self.cur_dir == 1:
                steps = min(num, self.height -1 - col)
                num -= steps
                col += steps
            elif self.cur_dir == 2:
                steps = min(num, row)
                num -= steps
                row -= steps
            else:
                steps = min(num, col)
                num -= steps
                col -= steps
            if num > 0:
                self.cur_dir = (self.cur_dir + 1) % 4
        self.cur = row, col

    def getPos(self) -> List[int]:
        return self.cur

    def getDir(self) -> str:
        return self.dir_mapping[self.cur_dir]

# Your Robot object will be instantiated and called as such:
# obj = Robot(width, height)
# obj.step(num)
# param_2 = obj.getPos()
# param_3 = obj.getDir()