How many random numbers do you want to generate? 8 What is the maximum value (inclusive) of the random numbers? 5 Random numbers: 3, 5, 3, 5, 5, 0, 3, 2 Number 0 occurs 1 time Number 1 occurs 0 times Number 2 occurs 1 time Number 3 occurs 3 times Number 4 occurs 0 times Number 5 occurs 3 times
For counting the occurrences in an array, it's useful to create another array, the counting array. The index of the counting array represents a number in the first array. The value at that index is the count for that number.
Since the range of our random numbers starts at 0, the length of this counting array should be one more than the maximum value of the random numbers: If the maximum value is 3, the length of the counting array should be 4 to count how often the numbers 0, 1, 2, and 3 occur in the random numbers array.
For example, if the array of random numbers is [1, 3, 0, 1, 2, 3], the counting array should be [1, 2, 1, 2] because:
| Value | 1 | 3 | 0 | 1 | 2 | 3 |
|---|
| Value | 1 | 2 | 1 | 2 |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |