Search code examples
c++arraysdice

Program to roll 2 dice 36000 times with possibilities


I have a C++ homework to do, this is the question

//Dietel & Dietel C Programming //Chapter 6 Arrays: Page 241 Exercise:
6.19 /* Write a program that simulates the rolling of two dice. 

* The program should use rand to roll the first die, and 
* should use rand again to roll the second die. 

* The sum of the two values should then be calculated. (Note: Since each die 
* can show an integer value from 1 to 6, then the sum of the two values will vary
* from 2 to 12 with 7 being the most freqent sum and 2 and 12 being the least frequent
* sums.) Figure 6.23 shows the 36 possible combinations of the two dice. 

* Your program should
* roll the two dice 36,000 times. Use a single-scripted array to tally the numbers of times 
* each possible sum appears. 

* Print the results in a tabular format. Also, determine if the totals 
* are resonable; i.e there are six ways to roll a 7, so approximately one sixth of all of the
* rolls should be 7. 
*/

I created the program, but it gives me the output like this:

sum of Faces    Frequency
      2            0
      3         4041
      4            0
      5         7922
      6            0
      7        12154
      8            0
      9         7936
     10            0
     11         3948
     12            0
sum: 36001

I don't why it's giving 0 frequency for all even numbers

Here's what I coded so far:

#include <iostream>
#include<iomanip>
using namespace std;

int main()
{

    const int arraysize = 13;

    int counter[13], sum=0;
    // init counter
    for(int i=0; i<13; i++)
        counter[i] = 0;

    int die1; 
    int die2;

    for ( int roll1 = 0; roll1 <=36000; roll1++ ) {
        die1 =  1 + rand() % 6;
        die2 =  1 + rand() % 6;
        counter[die1+die2]++;
    }

    cout<<"sum of Faces"<<setw(13)<<"Frequency"<<endl;

    for(int face=2; face<arraysize;face++)
    {
        cout<<setw(7)<<face<<setw(13)<<counter[face]<<endl;
        sum += counter[face];
    }

    cout << "sum: " << sum;


    return 0;
}

I need to add possibilities for the dice as well, example:

1 + 1 = 2 : 1 possibility for sum to be 2
1 + 2 = 2 + 1 = 3 : 2 possibility for sum to be 3
1 + 3 = 2 + 2 = 3 + 1 = 4 : 3 possibility for sum to be 4
.
.
.
6 + 6 = 12 : 1 possibility for sum to be 12

Solution

  • You don't seem to be seeding the random function, this can produce strange results

    Solution:

    #include <ctime>   // time()
    #include <cstdlib> // srand(), rand()
    
    ...
    
    srand(time(NULL)); // There are better ways to seed rand(), but this is simple
    
    ...
    
    for ( int roll1 = 0; roll1 <=36000; roll1++ ) {
        die1 =  1 + rand() % 6;
        die2 =  1 + rand() % 6;
        counter[die1+die2]++;
    }
    

    Also, if you want a more C++-like solution (and have access to C++11), check this out