Count how many votes a number has

Hi,

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.

This is the code I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  void gen(int x[]) {
    for (int i = 1; i < 1000; i++)
        x[i] = 1 + rand() % 3;
    }

void result(int x[]) {
    for (int i = 1; i < 1000; i++)
        cout << " " << x[i] << " ";
}

int main() {
    
    int random[1000];
    gen(random);
    srand((unsigned)time(NULL));
    
    result(random);
    
    return 0;
}


Thank you in advance
Array indices start at 0, not 1.
You should change your loops to
for (int i = 0; i < 1000; i++)

Also, call srand before you call gen.

If you know that only a set amount of numbers are possible (1, 2, 3), then just make an array of that size to keep track of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#include <iostream>
#include <ctime>
#include <cstdlib>

const int 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;
}
Last edited on
Thank you! I see. This is better than what I had now my computer doesn't lag when printing out all the numbers.

If you sort the numbers first, then you can just count how many of each identical number you have and go to the next larger or smaller number.
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.
Topic archived. No new replies allowed.