Can someone explain this program to me in further detail? It was written for the
ID: 646340 • Letter: C
Question
Can someone explain this program to me in further detail? It was written for the following question, I know there are many ways to write a program this specific way is confusing me I don;t understand why certain methods were used:
Given the following game: a pair of dice is rolled repeatedly. If "box cars" (6-6) shows up, player A wins. If not, but 7 shows up twice in a row, B wins. Should you choose to be A or B? Write a C++ program to a pair of dice 1000 times. Output how many times A and B would have won
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int die1, die2, store = 0, awin = 0, bwin = 0;
srand(time(NULL));
for(int i = 0; i < 1000; i++)
{
die1 = rand()% 6+1;
die2 = rand()% 6+1;
if(die1 == 6 && die2 == 6)
{
awin++;
}
else if (store == 7 && (die1 + die2) == 7)
{
bwin++;
}
store = die1 + die2;
}
cout << "A has won " << awin << " times and B has won " << bwin << " times." << endl;
system("pause");
}
Explanation / Answer
The code is exactly following what is asked in the question. So lets go step by step.
1) How would you simulate a dice throw in a c++ program(as the code is in c++)?
You will have to use a random number generator to do that. Once you have a random number, divide it by 6 and get the remainder to get an integer value in [0,5]. Now add 1 to this value to get an integer value in [1,6]
For generating a random number, C++ has an inbuilt function called "rand()" which can be used after including "time.h" header file. Now it needs some seed as an initialization value. That's why there is "srand(time(NULL));" in the code. You have to call srand() once in the program and you can now use rand() as many times as you like in the code.
As already explained earlier, for generating a random integer between [1,6] we can use "rand()%6+1" where % symbol is for the modulus(gives the remainder).
Now to simulate two dice throws, just call rand() twice.
2) How to simulate 1000 throws of two dices?
Just use for loop to iterate 1000 times and each time create two random dice throws.
Now,
a) First check whether both the dices have got 6 on them. This is done by the following code
if(die1 == 6 && die2 == 6)
{
awin++;
}
b) If this is not the case, then check whether the sum of numbers on both the dice is 7 or not. This is done by the following code
else if (store == 7 && (die1 + die2) == 7)
{
bwin++;
}
Here "store" is just a flag variable used to make sure that the previous thow also had the sum as 7.
Take the following example.
Case1: A wins
1st throw -> 1, 4
2nd throw -> 6, 6
Now the "If condition" is true and hence A wins.
Case 2-> B wins
1st throw -> 2, 6(store is set to 8)
2nd throw->2,5(sum=7 for the first time. So store is set to 7)
3rd throw-> 3,4(sum=7 again)
Now the "else condition" is true because store is equal to 7 and the current sum of the dices is also equal to 7. Hence B wins.