I have generated an array of 5 random integers from 1-5. Here is what the array looks like now: myArray[5] = {3, 3, 1, 4, 5}
I have now sorted the array of 5 integers in ascending order, from least to greatest.
myArray[5] = {1, 3, 3, 4, 5}
I now need to count the number of occurrences a specific integer has and make a table of it.
Such as:
Number: Count:
1:1
2:0
3:3
4:0
5:1
The farthest I've gotten has been looping through the array. I am having a hard time talling the numbers and creating a count of how many occurances there are.
Not using any maps, or iterations, etc. I am trying to get this count. Here is what I have tried already:
int counts[10];
for (int x = 0; x <= 10; x++){
int counter = 0;
for (int j = 0; j < ARRAY_SIZE; j++){
if (x == myArray[j]){
counts[x] == counter++;
}
}
cout << "Number: " << x << "Number of Occurances: " << counts[counter]<< "\n";
}
However, my output is incredibly wrong.
Make a hash and initialize with zero.
the hash at index arr[i] will hold value which is the count of occurrence of that number. As
hash[arr[i]]++
will increment the count at index equal to the value of arr[i]. This way we can check which value occurred how many times by checking hash[arr[i]] where arr[i] is value to be checked.Use a
std::map
to map integers to their counts.Now you can print the keys and values in
counts
. See How to loop through a C++ map of maps? for how to do this.You can do it with an array instead of a map. The only difference is that it won't automatically expand to handle larger values (unless you use
malloc
andrealloc
to make it dynamically sized).