Answer: Debug the Robot #332

Here’s the bug

Step 4 is an extra Forward that shouldn’t be there. Beep walks one square too far.

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. Forward
  2. Forward
  3. Turn left
  4. Forward
  5. Forward
  6. Forward
  7. Forward
  8. Forward
  9. Turn right
  10. Forward
  11. Forward
  12. Forward
  13. Turn left
  14. Forward

What the buggy program did

Here is what happens if Beep follows the program with the bug, step by step. Beep bumps into a wall.

StepCommandBeep is now atFacingNote
1Forwardcolumn 7, row 6up
2Forwardcolumn 7, row 5up
3Turn leftcolumn 7, row 5left
4Forwardcolumn 6, row 5left
5Forwardcolumn 5, row 5left
6Forwardcolumn 4, row 5left
7Forwardcolumn 3, row 5left
8Forwardcolumn 2, row 5left
9Forwardcolumn 1, row 5left
10Turn rightcolumn 1, row 5up
11Forwardcolumn 1, row 5upBump! A wall or the edge is in the way.

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 = "FFLFFFFFRFFFLF"
walls = [(0, 0), (0, 3), (0, 5), (3, 1), (4, 3), (5, 2), (6, 0), (7, 3)]
width, height = 8, 7
x, y, facing = 6, 6, "up"

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 (0, 1) facing left

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