Lesson 48: Count every colour
تحتاج هذه الصفحة إلى متصفح حديث (يدعم SharedArrayBuffer). يرجى تحديث Chrome أو Edge أو Firefox أو Safari إلى أحدث إصدار.
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.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
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.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Which colour is most common? Find the فهرس of the biggest count in best, then the program prints the colour and its count, for example Most: blue (3).
اضغط تشغيل لرؤية المخرجات هنا.