How to count the number of times that a random number is generated in a less cumbersome way?

advertisements

If a program should simulate a dice roll, and roll the dice any given number of times. How can a code be written, so it could count the times a number was rolled? I have a code below, but I think it's a tedious and ugly method to accomplish this task. I think there is a better way to do this, perhaps a very less cumbersome code. here is the code:

#include <iostream>
#include <ctime>

int main(int argc, const char * argv[]) {
    int roll, s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0, i, roll_times = 0;
    std::cout << "How many times do you want to roll the dice?" << std::endl;
    std::cin >> roll_times;
    srand(unsigned(time(NULL)));
    for(i = 0; i < roll_times; i++) {
        roll = rand() % 6 + 1;
        switch(roll) {
            case 1:
                s1++;
                break;
            case 2:
                s2++;
                break;
            case 3:
                s3++;
                break;
            case 4:
                s4++;
                break;
            case 5:
                s5++;
                break;
            case 6:
                s6++;
                break;
        }
    }
    std::cout << "The number 1  was rolled " << s1 << " times." << std::endl;
    std::cout << "The number 2  was rolled " << s2 << " times." << std::endl;
    std::cout << "The number 3  was rolled " << s3 << " times." << std::endl;
    std::cout << "The number 4  was rolled " << s4 << " times." << std::endl;
    std::cout << "The number 5  was rolled " << s5 << " times." << std::endl;
    std::cout << "The number 6  was rolled " << s6 << " times." << std::endl;
    return 0;
}


Instead of having individual variables, you can utilize an array of 6 integers. Then make use of the indices in the first for-loop to set your counts. The same idea can be applied to your output to the screen.

int main(int argc, const char * argv[]) {
    int roll, i, roll_times = 0;
    int dice[6] = {0};
    cout << "How many times do you want to roll the dice?" << endl;
    cin >> roll_times;
    srand(unsigned(time(NULL)));
    for(i = 0; i < roll_times; i++)
    {
        roll = rand() % 6;
        dice[roll]++;
    }
    for(int k = 1; k <= 6; k++)
    {
        cout << "The number " << k << " was rolled " << dice[k-1] << " times." << endl;
    }
    return 0;
}