2
Count and combine
Computing 3: Unit 1, pp. 8–27
GoalSpot repeated blocks, combine them, count the blocks and check that the shorter program does the same job.
New words
pattern · something that repeats in the same waycombine · to join several things into onecompare · to look at two things and see how they are the same or different
Explanation
To make a program concise, look for patterns. A pattern is a block that repeats, side by side. We combine the repeats into one block with a bigger number. Then we count the blocks again. Fewer blocks should mean the same result, so always compare the two programs. They should end in the same place, at the same size. Take care: if another block sits between two blocks, they are not side by side.
Worked examples
| Program A | Program B | |
|---|---|---|
| x at the end | −100 + 20 + 20 + 20 = −40 | −100 + 60 = −40 |
| size at the end | 100 + 10 + 10 = 120 | 100 + 20 = 120 |
| blocks | 6 | 3 |
| Long algorithm | Short algorithm |
|---|---|
| Water plant | Water 4 plants |
| Water plant | Pull 2 weeds |
| Water plant | |
| Water plant | |
| Pull weed | |
| Pull weed |
Do these programs do the same? A moves 10, then turns, then moves 10. B moves 20, then turns. No. In A the sprite turns before its second move, so it ends in a different place. Only blocks that are side by side can be joined.
Class activity
Pattern hunt (with a friend): write a long list of actions on a strip of paper, for example “clap, clap, stamp, stamp, stamp, jump”. Underline the groups of repeated actions. Rewrite the list in the shortest way: “Clap 2 times, Stamp 3 times, Jump”. Count the steps in each list. Then do both lists out loud. Do they feel the same?
Practice
1
Make this program more concise. Which blocks repeat, and how many blocks does the new program have?
The three “change size by (5)” blocks become “change size by (15)”. The three “change y by (10)” blocks become “change y by (30)”. The new program has 3 blocks (the hat and 2 more).
2
Here is a baker’s algorithm. Rewrite it with joined steps. How many steps does your algorithm have?
| Step | Instruction |
|---|---|
| 1 | Add a scoop of flour |
| 2 | Add a scoop of flour |
| 3 | Add a scoop of flour |
| 4 | Stir |
| 5 | Add an egg |
| 6 | Add an egg |
| 7 | Bake |
Add 3 scoops of flour. Stir. Add 2 eggs. Bake. It has 4 steps instead of 7. (The Stir step sits between the flour and the eggs, so it stays on its own.)
3
A program has 10 blocks. Two pairs of blocks are joined into one block each. How many blocks does the new program have?
8 blocks. Each pair becomes one block, so we save 2 blocks.
4
Do programs A and B do the same job? Explain.
No. In A the sprite moves up 20 + 20 + 20 = 60. In B it moves up only 50. The size change is the same, but the end place is different.