Answer: Debug the Robot #319

Here’s the bug

Step 10 says Turn left, but it should say Turn right. Beep turned the wrong way!

Did you find a different fix that also gets Beep to the battery? That counts too! There is often more than one way to fix a bug. The important thing is that you tested it step by step.

The fixed program, with Beep's route to the battery drawn as an orange line.
With the bug fixed, Beep reaches the battery.

The fixed program

  1. Turn left
  2. Turn left
  3. Forward
  4. Turn left
  5. Forward
  6. Forward
  7. Forward
  8. Forward
  9. Forward
  10. Turn right
  11. Forward

What the buggy program did

Here is what happens if Beep follows the program with the bug, step by step. Beep doesn’t bump into anything, but ends up in the wrong square.

StepCommandBeep is now atFacingNote
1Turn leftcolumn 3, row 6down
2Turn leftcolumn 3, row 6right
3Forwardcolumn 4, row 6right
4Turn leftcolumn 4, row 6up
5Forwardcolumn 4, row 5up
6Forwardcolumn 4, row 4up
7Forwardcolumn 4, row 3up
8Forwardcolumn 4, row 2up
9Forwardcolumn 4, row 1up
10Turn leftcolumn 4, row 1left
11Forwardcolumn 3, row 1left

Check it with Python

This Python program pretends to be Beep. It follows the fixed program and checks for walls on the way. In Python, squares are counted from 0, so column 1, row 1 is (0, 0).

program = "LLFLFFFFFRF"
walls = [(0, 3), (1, 2), (1, 5), (2, 2), (4, 2), (6, 0), (6, 4), (6, 5)]
width, height = 7, 6
x, y, facing = 2, 5, "left"

moves = {"up": (0, -1), "right": (1, 0), "down": (0, 1), "left": (-1, 0)}
turn_left = {"up": "left", "left": "down", "down": "right", "right": "up"}
turn_right = {"up": "right", "right": "down", "down": "left", "left": "up"}

for step in program:
    if step == "F":
        dx, dy = moves[facing]
        if (x + dx, y + dy) in walls or not (0 <= x + dx < width and 0 <= y + dy < height):
            print("Bump! Beep hit a wall at", (x, y))
            break
        x, y = x + dx, y + dy
    elif step == "L":
        facing = turn_left[facing]
    elif step == "R":
        facing = turn_right[facing]

print("Beep finished at", (x, y), "facing", facing)

When you run it, it prints:

Beep finished at (4, 0) facing right

The battery is at (4, 0) in Python’s counting, so Beep made it! Try putting the buggy program, "LLFLFFFFFLF", back in and see what Python says.