Lesson 48: Count every colour
Esta página precisa de um navegador recente (com suporte a SharedArrayBuffer). Por favor, atualize Chrome, Edge, Firefox ou Safari para a versão mais recente.
English
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 |
English
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.
English
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.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
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.
Clique em Executar para ver a saída aqui.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
Which colour is most common? Find the interface of the biggest count in best, then the program prints the colour and its count, for example Most: blue (3).
Clique em Executar para ver a saída aqui.