Lesson 48: Count every colour
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Two lists, one index
- Instead of three variables (
red_count,green_count,blue_count), keep the counts in one list. - A second list holds the names. The same index joins them: index 0 is red in both.
- Lists that go together like this are often called parallel arrays.
| Index | colours | counts (map 1) |
|---|---|---|
| 0 | "red" | 2 |
| 1 | "green" | 2 |
| 2 | "blue" | 3 |
Why use lists?
- One loop prints every colour. With 10 colours, the loop does not get longer.
- To find the most common colour, find the index of the biggest count. Then
colours[best]gives its name. - Exam programs often keep data like this, for example names in one array and marks in another.
In the exam
- 0478/21/M/J/24 Q10 (the long programming question): the array Clubs[] holds the names of 12 cricket clubs and Points[] their points. The question says: "The position of any cricket club's data is the same in all three arrays". Among other things, the program must find the club with the highest number of points and output its name. That is your second program: find the index of the biggest value, then use the same index in the names array.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
The robot drives over 8 places with red, green and blue tiles. Two lists go together: colours[i] is a colour and counts[i] is how many of it the robot has seen. Red is done. Count green in counts[1] and blue in counts[2], then print each colour and its count on its own line, with a loop: red: 2.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Which colour is most common? Find the index of the biggest count in best, then the program prints the colour and its count, for example Most: blue (3).
Click Run to see the output here.