Rolling of a pair of dice 1000 times
Question
Use a loop to simulate the rolling of a pair of dice 1000 times.
1) Use the function provided named roll to simulate the rolling of a single dice.
2) a function named rollDice to simulate the rolling of two dice by calling the roll function twice
3) Count the number of times each value from 2 to 12 occurred. You will need a separate counter for each value. If the value is 2, then increment its counter. If the value is 3, then increment its counter, etc.
4) Display the result of each of the counters.
Summary
We know that dice have six phases and there are numbers from 1 to 6 at every phase. When we roll the dice, any number from 1 to 6 can come at the top. So here we will roll two dices together and we get the random numbers on both dices from 1 to 6. We take the sum of both dices as the result. So here we have rolled the dices one thousand times. We have noted the occurrences of the sum that is between 2 and 12. We have to console the output as the sum from 2 to 12 with their frequency.
Explanation
In order to solve this question in the C++ language, we have defined a function with the name rollTheDice(), and this function will return a random integer between 1 and 6. This function will use the rand() predefined function to generate the random numbers between 1 and 6. These random integers will work as the number we got on rolling the dices. We have done the calculation (rand()%6) in order to get the result between 1 and 6. It will generate the number from 0 to 5 and we will add 1 to get the number between 1 and 6. We have defined another function also. This function is rollPairDice(), which will give us the summation of the result on the dices. In the main method, we will declare a counter array, and we will declare all the values as 0. Then, we will increment the counter at each index on occurring that value when rollPairDice is called. We will call the rollPairDice() function one thousand times. And at last, we will print the counter of each value between 2 and 12 as output. We will count the occurrence of the number.
The counts obtained will change all the time, since the dice value occurrence is random.
Code
#include <iostream> using namespace std; #include <stdlib.h> #include <iomanip> /* to roll two dice and take their sum */ int rollPairDice(){ /* calling two roll functions */ int sum=rollTheDice()+rollTheDice(); return sum; } /* to roll a die randomly */ int rollTheDice(){ /* random value to be between 1 and 6 */ return (rand()%6)+1; } /* driver */ int main() { /* to store the count of each value */ int freq[13]={0,0,0,0,0,0,0,0,0,0,0,0,0}; for(int i=0;i<1000;i++){ freq[rollPairDice()]++; } cout<<left; /* to display the result */ cout<<setw(8)<<"Value"<<setw(10)<<"Count"<<endl; for(int i=2;i<=12;i++){ cout<<setw(8)<<i<<setw(10)<<freq[i]<<endl; } }
Output
Also read, Consider the use of the recursive MergeSort algorithm to sort a sequence of n elements.