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 a second array. The index of the second array represents a number in the first array. The value at that index is the count for that number.
For example, if the first array consists of the numbers [1, 0, 1, 3, 0, 3]
, the second array would be [2, 2, 0, 2]
because the number 0 occurs 2 times, the number 1 occurs 2 times, the number 2 occurs 0 times, and the number 3 occurs 2 times.
The length of this second array should be one more than the maximum value of the random numbers: If the maximum value is 3, the length of the second array should be 4 to count how often the numbers 0, 1, 2, and 3 occur in the first array.
Value | 1 | 0 | 1 | 3 | 0 | 3 |
---|
Value | 2 | 2 | 0 | 2 |
---|---|---|---|---|
Index | 0 | 1 | 2 | 3 |