Lesson 48: Count every colour
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
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.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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).
Nhấn Chạy để xem kết quả ở đây.