Answer: Debug the Robot #351

Here’s the bug

A Forward step is missing. It should come after step 11. Without it, Beep turns too early.

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. Forward
  3. Turn left
  4. Forward
  5. Forward
  6. Turn right
  7. Forward
  8. Turn left
  9. Forward
  10. Forward
  11. Turn left
  12. Forward
  13. 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 2, row 5down
2Forwardcolumn 2, row 6down
3Turn leftcolumn 2, row 6right
4Forwardcolumn 3, row 6right
5Forwardcolumn 4, row 6right
6Turn rightcolumn 4, row 6down
7Forwardcolumn 4, row 7down
8Turn leftcolumn 4, row 7right
9Forwardcolumn 5, row 7right
10Forwardcolumn 6, row 7right
11Turn leftcolumn 6, row 7up
12Forwardcolumn 6, row 6up

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

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