AdvertisementYour brand could be hereYour brand hereOn every Darslab page · students, parents and teachersinfo@darslab.comAsk for pricesPricesinfo@darslab.com
☰ Year plan · Computing

Efficient algorithms

Week 8 · Unit 4: Be a designer · 3 lessons
2

Fewer steps, same route

Computing 3: Unit 4, pp. 60–78
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)
StartStart
Move 1Move 2
Move 1Turn right
Turn rightMove 1
Move 1Turn left
Turn leftMove 3
Move 1Stop
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.
forwardturn rightturn leftforward
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.

Practice
1
Rewrite this algorithm with fewer steps.
StepInstruction
1Start
2Move 1
3Move 1
4Move 1
5Turn left
6Move 1
7Move 1
8Stop
2
Write these robot cards with fewer cards.
forwardforwardforwardturn rightforwardforward
3
Join these steps if you can: Move 2, Move 3, Move 1.
4
How can “Turn right, Turn left, Move 2” be made shorter?