Answer: Debug the Robot #337

Here’s the bug

Steps 14 and 15 are in the wrong order. It should be Forward and then Turn left, not the other way round.

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. Forward
  5. Turn left
  6. Forward
  7. Forward
  8. Forward
  9. Forward
  10. Forward
  11. Forward
  12. Turn left
  13. Forward
  14. Forward
  15. Turn left
  16. 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
1Turn leftcolumn 6, row 7down
2Turn leftcolumn 6, row 7right
3Forwardcolumn 7, row 7right
4Forwardcolumn 8, row 7right
5Turn leftcolumn 8, row 7up
6Forwardcolumn 8, row 6up
7Forwardcolumn 8, row 5up
8Forwardcolumn 8, row 4up
9Forwardcolumn 8, row 3up
10Forwardcolumn 8, row 2up
11Forwardcolumn 8, row 1up
12Turn leftcolumn 8, row 1left
13Forwardcolumn 7, row 1left
14Turn leftcolumn 7, row 1down
15Forwardcolumn 7, row 1downBump! 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 = "LLFFLFFFFFFLFFLF"
walls = [(0, 2), (2, 0), (2, 1), (2, 3), (4, 0), (4, 1), (4, 4), (5, 2), (6, 1)]
width, height = 8, 7
x, y, facing = 5, 6, "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 (5, 1) facing down

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