GoalRewrite an algorithm with fewer steps by joining moves that are side by side and removing steps that cancel out.
New words
rewrite · to write something again with changescancel out · to undo each other, so that nothing changestotal · all the parts added together
Explanation
To make an algorithm efficient, first follow it and see what it does. Then look for moves that are the same and side by side, and join them. “Move 2, Move 3” becomes “Move 5”, when nothing comes between them. A turn between two moves stops you joining them. Also look for steps that cancel out. “Turn right, Turn left” puts the robot back to the way it faced, so both steps can go. At the end, follow the new algorithm. It must make the same route.
Worked examples
Long (10 steps)
Short (7 steps)
Start
Start
Move 1
Move 2
Move 1
Turn right
Turn right
Move 1
Move 1
Turn left
Turn left
Move 3
Move 1
Stop
Move 1
Move 1
Stop
This route goes up 2, right 1 and up 3. The long algorithm has 10 steps. The short one has 7 steps, with the repeated moves joined. Count the steps in both tables.
Moves can be joined only when nothing sits between them. “Move 2, Move 3” becomes “Move 5”, because both go the same way. But in “Move 2, Turn left, Move 3” the turn is in the middle, so the two moves stay apart.
These steps cancel out: “Turn right, then turn left”. The robot faces the same way as before. So “Move 1, Turn right, Turn left, Move 1” can be written as “Move 2”.
Class activity
Shorten the route (with a friend): write an algorithm for walking across the room that has at least eight steps, including some steps that repeat. Swap with your friend. Rewrite your friend’s algorithm with fewer steps, then follow both versions. Do you finish in the same place? Count how many steps you saved.