I am wondering how would I go about counting the amount of votes a certain number has in an array. I have 100 random numbers between 1-3 and I need to count how many each each number has for example:
Number 3 was voted for x amount of times
I know it would be a for loop but I'm not sure how its done.
#include <iostream>
#include <ctime>
#include <cstdlib>
constint Num_Results = 3;
void gen(int x[], int results[]) {
for (int i = 0; i < 1000; i++) {
x[i] = 1 + rand() % Num_Results;
results[x[i] - 1]++; // x[i] - 1 is either a 0, 1, or 2.
}
}
void result(int x[], int results[]) {
for (int i = 0; i < Num_Results; i++)
{
std::cout << "The number " << i + 1 << " occurred " << results[i] << " times.\n";
}
// Print the actual array here if you want to (pass in the random array)
}
int main() {
int random[1000];
int results[Num_Results] = {}; // initialize all numbers to 0
srand((unsigned)time(NULL));
gen(random, results);
result(random, results);
return 0;
}
SamuelAdams: I don't think sorting is appropriate here. It would almost certainly take more CPU (probably MUCH more) than simply iterating through the array and updating a few counters.