【问题标题】:Move Robot in a 10 X 10 grid在 10 X 10 网格中移动机器人
【发布时间】:2021-04-21 19:13:56
【问题描述】:

我正在处理这个代码挑战:

给定一个只能在四个方向上移动的 2D 机器人/机器人,在 10x10 网格中向前移动是 UP(U),向后移动是 DOWN(D)、LEFT(L)、RIGHT(R)。机器人不能超出 10x10 的区域。

给定一个包含移动指令的字符串。

执行指令后输出机器人的坐标。机器人初始位置在原点(0, 0)。

Example:
Input : move = “UDDLRL” 
Output : (-1, -1)
Explanation:
Move U : (0, 0)–(0, 1)
Move D : (0, 1)–(0, 0)
Move D : (0, 0)–(0, -1)
Move L : (0, -1)–(-1, -1)
Move R : (-1, -1)–(0, -1)
Move L : (0, -1)–(-1, -1)
Therefore final position after the complete
movement is: (-1, -1)

我在不使用 10x10 网格信息的情况下使代码正常工作。如何以 OOP 方式将 10x10 网格信息合并到我的解决方案中?我的解决方案不遵循 OOP 原则。

# function to find final position of
# robot after the complete movement

def finalPosition(move): 
    l = len(move)
    countUp, countDown = 0, 0
    countLeft, countRight = 0, 0
 
    # traverse the instruction string 'move'
    for i in range(l): 
        # for each movement increment its respective counter
        if (move[i] == 'U'):
            countUp += 1
        elif(move[i] == 'D'):
            countDown += 1
        elif(move[i] == 'L'):
            countLeft += 1
        elif(move[i] == 'R'):
            countRight += 1
 
    # required final position of robot
    print("Final Position: (", (countRight - countLeft),
          ", ", (countUp - countDown), ")")
 
 
# Driver code
if __name__ == '__main__':
    move = "UDDLLRUUUDUURUDDUULLDRRRR"
    finalPosition(move)

【问题讨论】:

  • 使用 10x10 网格与没有 10x10 网格的代码有何不同?
  • 我想知道我是否应该先创建一个 10X10 的网格。这个问题只是陈述了一个 10 X 10 的网格。我猜机器人不能超出 10 X 10 的区域。
  • 那么你应该检查你的计数不能变成负数并且不能超过9,对吧?你试过了吗?
  • 我明白了。会试一试。 @trincot
  • @trincot 现在使用您的解决方案更有意义。 +1

标签: python-3.x oop robot


【解决方案1】:

这解决了它:

class Robot:

    class Mover:
        def __init__(self, x, y):
            self.x, self.y = x, y

        def new_pos(self, x, y):
            new_x = x + self.x
            new_y = y + self.y
            if (new_x > 9 or new_y > 9):
                raise ValueError("Box dimensions are greater than 10 X 10")
            return new_x, new_y

    WALKS = dict(U=Mover(0, 1), D=Mover(0, -1),
                 L=Mover(-1, 0), R=Mover(1, 0))

    def move(self, moves):
        x = y = 0
        for id in moves:
            x, y = self.WALKS[id].new_pos(x, y)
        return (x,y)

if __name__ == '__main__':
    moves2 = "UDDLLRUUUDUURUDDUULLDRRRR"
    robot = Robot()
    print(robot.move(moves2))

输出:

(2,3)

【讨论】:

  • 这允许机器人以负 X 和 Y 值移动到 10x10 网格之外,当机器人试图从另外两侧移动到外面时会产生错误。问题中未指定应触发错误。它只是说机器人不能移动到该区域之外,所以我假设机器人会忽略这些移动(就像撞到栅栏一样)。此外,如果您多次调用move,机器人不会从最后一个位置继续。机器人并不真正记住它的位置,这不是真正的 OOP 风格。
  • 当您允许机器人移动到负偏移量而不是大于 9 的偏移量时,您能解释一下为什么您认为这是正确答案吗?我没有看到其中的一致性......
【解决方案2】:

您使用计数器的方式使检测到您会碰到 10x10 网格的边界变得不那么简单了。不用太多改动,你可以将countUpcountDown变量替换为一个countVertical变量,上升时加-1,下降时加1。如果它会使计数器变为负数或大于 9,则忽略一个移动。显然,你会为水平移动做同样的事情。

[编辑:在对您的问题进行编辑后,事实证明您希望 Y 坐标与我上面假设的相反。所以我改变了 Y 坐标更新的符号(+1,-1)。]

原来如此。

现在为了使这更加 OOP,您可以定义一个 Robot 类,该类将保持其 xy 坐标。无论如何,最好从您的函数中删除 print 调用,因此该函数只处理运动,而不是报告(关注分离)。

这是它的工作原理:

class Robot:
    def __init__(self, x=0, y=0):
        self.position(x, y)
 
    def position(self, x, y):
        self.x = min(9, max(0, x))
        self.y = min(9, max(0, y))

    def move(self, moves):
        for move in moves:
            if move == 'U': 
                self.position(self.x, self.y + 1)
            elif move == 'D':
                self.position(self.x, self.y - 1)
            elif move == 'L':
                self.position(self.x - 1, self.y)
            elif move == 'R':
                self.position(self.x + 1, self.y)
            else:
                raise ValueError(f"Invalid direction '{move}'")
  
if __name__ == '__main__':
    moves = "UDDLLRUUUDUURUDDUULLDRRRR"
    robot = Robot(0, 0)
    robot.move(moves)
    print(f"Final position: {robot.x}, {robot.y}")

【讨论】:

  • 不是 1 个月后。仅仅5天后。我没有改变问题,只是添加了一个示例输入/输出。
  • 对不起那个月。示例输出显示向上的方向与我的假设不同。
猜你喜欢
  • 2022-11-08
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2013-03-01
  • 2017-08-27
  • 1970-01-01
相关资源
最近更新 更多