Week 28 · Unit 12: Be a problem solver · 3 lessons
3
Pick once, test often
Computing 5: Unit 12, pp. 159–170
GoalTrace a micro:bit program that picks a random number once and tests the stored value with equal-to.
New words
pick random · a block that chooses a whole number by chance between two limitsequal to · the test = that is true when two values are the samevariable · a named place that stores a valuemicro:bit blocks · the picture blocks that program a micro:bit board
Explanation
A micro:bit can pick a random number between two limits. The program should store this number in a variable, once, and then test the variable with the equal-to block. This is efficient and correct. If a program calls pick random again inside every test, each test gets a new number. Then the board may show two pictures, or none. So pick once, then test the stored value as often as needed. A variable holds one value at a time, so only one of the tests ‘mood = 1’, ‘mood = 2’ and ‘mood = 3’ can be true.
Worked examples
Press
mood
Test that is true
Board shows
1
2
mood = 2
asleep face
2
3
mood = 3
surprised face
3
3
mood = 3
surprised face
4
1
mood = 1
happy face
This is the correct mood board, shown above. On four presses of the logo the board picks 2, 3, 3 and 1. Each press picks only one number and shows one picture.
Here is a wrong version. Each if block has its own pick random, so the three tests use three different numbers.
Three numbers picked
Pictures shown by the wrong version
2, 3, 1
none
1, 1, 3
happy, then surprised
1, 2, 3
happy, asleep, surprised
In the wrong version the three numbers can be any of 1, 2 and 3. Sometimes no picture is shown, and sometimes there are two or three. The correct version always shows exactly one.
Class activity
Dice mood board (pairs, a die, paper). Draw three faces on paper: happy, asleep and surprised. Correct way: roll the die once, write the number in a cup labelled mood (1–2 means 1, 3–4 means 2, 5–6 means 3) and then check the three tests against the cup. Wrong way: roll the die again for each test. Do each way 10 times. In how many of the 10 rounds did you get exactly one picture, each way?
Practice
1
The board picks 3, 1 and 2 on three presses of button B. What does it show each time?
Press 1: Wait. Press 2: Go. Press 3: Stop.
2
A variable holds a random number from 1 to 3. How many different results are possible? How many of them show a picture if the tests are for 1 and 2 only?
There are 3 possible results. Two of them (1 and 2) show a picture, and 3 shows nothing.
3
What is wrong with this program, and how can you fix it?
Each test picks a new random number, so the board may show two icons or none. Fix: pick the number once and store it in a variable, then test the variable.
4
A program picks a number from 1 to 4 and has tests only for 1, 2 and 3. On how many of the 4 possible numbers is nothing shown?
On 1 of the 4 numbers: number 4 does not match any test, so nothing is shown.