Developing Algorithms
How to tell whether two algorithms do the same thing, how a conditional and a Boolean expression can say the same thing, and how new algorithms are built from ones you already trust, including a robot's path through a maze.
1What an algorithm is
An algorithm is a finite set of instructions that accomplishes a specific task. A recipe, directions to a friend's house, and a program that adds up a list are all algorithms. They can be written in everyday language, drawn as diagrams such as flowcharts, or written in pseudocode; a program carries one out in a programming language.
Every algorithm can be built from three ways of arranging steps: sequencing (steps in order), selection (choosing steps with IF), and iteration (repeating steps with a loop). Developing an algorithm means choosing and arranging those pieces, and then checking that the result really does the job.
2Same job, different code
Algorithms can be written in different ways and still do the same task, and different algorithms can be developed to solve the same problem. Here are two ways to add up a list called nums:
total ← 0
FOR EACH n IN nums
{
total ← total + n
}
DISPLAY(total)
total ← 0
i ← LENGTH(nums)
REPEAT UNTIL (i = 0)
{
total ← total + nums[i]
i ← i - 1
}
DISPLAY(total)
They look nothing alike, but for nums = [4, 7, 1, 8] both display 20. (They also agree on a one-item list, a list with a zero in it, and an empty list.) The reverse is just as true: algorithms that look similar can give different results. This one differs from B in only a starting value and a stopping value:
total ← 0
i ← 1
REPEAT UNTIL (i = LENGTH(nums))
{
total ← total + nums[i]
i ← i + 1
}
DISPLAY(total)
It displays 12. The loop stops as soon as i equals LENGTH(nums), before it adds the last item, 8. Looking at code is not enough to decide whether two algorithms match: trace them on the same input, and pick inputs that test the edges.
3Result versus side effect
The result of an algorithm is the value it produces: what it returns or displays at the end. A side effect is any other change it leaves behind, such as a list that was rearranged or shortened, or a variable that was overwritten. Two algorithms can have the same result and different side effects.
PROCEDURE largest(nums)
{
best ← nums[1]
FOR EACH n IN nums
{
IF (n > best)
{
best ← n
}
}
RETURN(best)
}
PROCEDURE largest(nums)
{
REPEAT UNTIL (LENGTH(nums) = 1)
{
IF (nums[1] < nums[2])
{
REMOVE(nums, 1)
}
ELSE
{
REMOVE(nums, 2)
}
}
RETURN(nums[1])
}
Both are called the same way:
scores ← [62, 91, 78, 85] DISPLAY(largest(scores)) DISPLAY(scores)
| Version | Displayed result | scores afterward |
|---|---|---|
| A | 91 | [62, 91, 78, 85] (unchanged) |
| B | 91 | [91] (three scores removed) |
Same result, 91. But version B removed items from the very list it was given, so the caller's scores list is now just [91]. If the program later needs the other scores, version B has broken it. When you compare algorithms, compare both what they produce and what they change.
4Conditionals and Boolean expressions
Some conditional statements can be written as an equivalent Boolean expression, and some Boolean expressions can be written as an equivalent conditional. The clearest case is an IF whose two branches only set a variable to true or false:
IF (temp < 0)
{
frozen ← true
}
ELSE
{
frozen ← false
}
does the same as the single line frozen ← temp < 0, because temp < 0 already is true or false. Two more pairs that always agree:
| This conditional | is equivalent to |
|---|---|
IF (age ≥ 16)
{
IF (hasPermit)
{
DISPLAY("may drive")
}
} | IF (age ≥ 16 AND hasPermit)
{
DISPLAY("may drive")
} |
IF (NOT raining)
{
DISPLAY("walk")
}
ELSE
{
DISPLAY("bus")
} | IF (raining)
{
DISPLAY("bus")
}
ELSE
{
DISPLAY("walk")
} |
A nested IF with no ELSE means both conditions must be true, which is what AND means. And NOT in front of a condition can be removed by swapping the two blocks. A program checked each pair for every combination of inputs; none disagreed.
5Building from known algorithms
Algorithms can be created from an idea, by combining existing algorithms, or by modifying an existing one. Knowing some standard algorithms makes new ones much easier to build. Four come up again and again:
| Known algorithm | Core idea | On [12, 5, 30, 7] |
|---|---|---|
| Maximum or minimum of two or more numbers | Keep the best so far; replace it when something beats it | max 30, min 5 |
| Sum or average of two or more numbers | Running total; divide by how many | sum 54, average 13.5 |
| Is one integer evenly divisible by another? | n MOD d = 0 (the remainder is 0) | 21 MOD 7 = 0: divisible |
| A robot's path through a maze | Move, turn, check the square ahead | see Figure 2 |
best ← nums[1]
FOR EACH n IN nums
{
IF (n > best)
{
best ← n
}
}
Modifying it into a minimum takes one change: flip > to < (and rename the variable so the code stays readable). Combining pieces gives something new: “average of the even numbers in a list” is the divisibility test, the running total and count, and the average step.
total ← 0
count ← 0
FOR EACH n IN nums
{
IF (n MOD 2 = 0)
{
total ← total + n
count ← count + 1
}
}
average ← total / count
DISPLAY(average)
For [3, 8, 5, 12, 10] it displays 10. For [3, 5, 9], with no even numbers, count stays 0 and the division total / count stops the program with an error. Each piece worked on its own; the problem is at the seam. Checking count = 0 before dividing fixes it.
Building from existing correct algorithms reduces development time (nothing is written twice), reduces testing (only the new joins need new tests), and makes errors easier to find (the trusted pieces are already ruled out).
Different code can do the same job, and similar code can do different jobs: trace on the same inputs, and compare both results and side effects. New algorithms are usually old ones combined or modified, and their errors tend to sit at the joins.
6A robot in a maze
Finding a robot's path through a maze is one of the standard algorithms. The robot sits in one square of a grid and faces one direction. It understands four commands:
| Command | What it does |
|---|---|
MOVE_FORWARD() | Moves one square in the direction the robot is facing |
ROTATE_LEFT() | Turns 90 degrees left (counterclockwise) without moving |
ROTATE_RIGHT() | Turns 90 degrees right (clockwise) without moving |
CAN_MOVE(direction) | true if the square in that direction (forward, backward, left, or right, measured from where the robot faces) is open and on the grid |
If MOVE_FORWARD() would take the robot into a blocked square or off the grid, the robot stays where it is and the program ends. Here the robot starts in the bottom-left square facing up:
REPEAT 4 TIMES
{
MOVE_FORWARD()
}
ROTATE_RIGHT()
REPEAT 4 TIMES
{
MOVE_FORWARD()
}
ROTATE_RIGHT()
REPEAT 4 TIMES
{
MOVE_FORWARD()
}
ROTATE_LEFT()
REPEAT 4 TIMES
{
MOVE_FORWARD()
}
The second program uses the same commands in a different order and never reaches the goal: after two squares to the right, the square ahead is blocked, so its third MOVE_FORWARD() ends the program. Track the robot's square and the way it faces after every command, and the mistake shows up immediately.
CAN_MOVE lets one algorithm work without counting squares. This version moves until blocked, turns right, and moves until blocked again:
REPEAT UNTIL (NOT CAN_MOVE(forward))
{
MOVE_FORWARD()
}
ROTATE_RIGHT()
REPEAT UNTIL (NOT CAN_MOVE(forward))
{
MOVE_FORWARD()
}
On this maze it follows the same path to the goal. Because it does not depend on the number 4, it also works on a taller or wider grid with the same shape.
7Worked examples
Same last value, different output
Do these segments produce the same output? Do they end with the same value of x?
x ← 0
REPEAT 3 TIMES
{
x ← x + 2
DISPLAY(x)
}
x ← 0
REPEAT 3 TIMES
{
DISPLAY(x)
x ← x + 2
}
- 1First segment: add, then display, three times:
2 4 6. - 2Second segment: display, then add:
0 2 4. - 3Both add 2 three times, so both end with
x= 6.
Pass or fail
Which single assignment is equivalent to this conditional for every score: passed ← score ≥ 60, passed ← score > 60, or passed ← NOT (score ≥ 60)?
IF (score ≥ 60)
{
passed ← true
}
ELSE
{
passed ← false
}
- 1The IF sets
passedto true wheneverscore ≥ 60is true, and false otherwise. - 2
score > 60gives false for a score of 60, but the IF gives true. - 3
NOT (score ≥ 60)gives the opposite answer for every score.
passed ← score ≥ 60. A program checked all three against the IF for every score from 0 to 100.Count multiples of 3
Write an algorithm that displays how many numbers in nums are divisible by 3, and trace it on [9, 14, 21, 4, 30].
- 1Pieces: a traversal of the list, the divisibility test
n MOD 3 = 0, and a counter. - 2Put the test inside the traversal and add 1 when it passes:
count ← 0 FOR EACH n IN nums { IF (n MOD 3 = 0) { count ← count + 1 } } DISPLAY(count) - 39 MOD 3 = 0 (count 1), 14 MOD 3 = 2, 21 MOD 3 = 0 (count 2), 4 MOD 3 = 1, 30 MOD 3 = 0 (count 3).
3.Second-largest value
A student modified the maximum algorithm to find the second-largest value. It works on [5, 9, 14] but not on [14, 9, 5]. Find and fix the problem. (Assume the values are positive and not all equal.)
first ← nums[1]
second ← nums[1]
FOR EACH n IN nums
{
IF (n > first)
{
second ← first
first ← n
}
}
DISPLAY(second)
- 1On [5, 9, 14], each value beats
first, so the old maximum slides intosecond: it displays9. - 2On [14, 9, 5], 9 and 5 never beat 14, so
secondis never updated and stays 14: it displays14. - 3The missing case: a value smaller than
firstbut bigger thansecond. Startsecondbelow every value and add that case:first ← nums[1] second ← -1 FOR EACH n IN nums { IF (n > first) { second ← first first ← n } ELSE { IF (n > second AND n < first) { second ← n } } } DISPLAY(second)
8Common mistakes
Similar code can give different results, and very different code can give the same result. Trace both on the same inputs, including edge cases.
Two algorithms that agree on one input may disagree on another. One disagreement proves they differ; agreeing on every input is what makes them equivalent.
Two procedures can return the same value while one also changes the list it was given. Compare what changes, not only what comes out.
ROTATE commands turn the robot without moving it, and left and right are measured from the way it faces. Write down the square and the direction after every command.
“Both procedures return 91 for [62, 91, 78, 85], so they have the same result. Version B also removes items from the list it is given, leaving [91], so it has a side effect that version A does not.”
Name the input you used, the result of each, and any change each leaves behind.