In: Computer Science
C++ , Write an iterative routine that will have 2 queues. Loop for 100 times and in the loop roll two die and place the first result into the queue1 and second into queue2. Then dequeue the rolls one at a time from each, printing each pair, and count how many times two rolls either add up to 7 or are doubles (i.e. same value). After the queues are empty, print out the number of 7s and doubles.
Assume srand has already been done.
we will use rand() function here to generate random numbers between range(1 to 6) which is dies range.
1+ rand()%6 (rand()%6 generates random number in range 0 to 5 we added 1 to make range 1 to 6)
first we iterate 100 times and inserted values in queue q1 and q2;
Then we popped out elements from queue and counted pair with sum 7 or pair that doubles(both value same).
following is the full code with comments.
#include<bits/stdc++.h>
using namespace std;
int main()
{
queue<int> q1,q2;//declaring 2 queues
srand(time(0));//in question given that it is done before
for(int i=1;i<=100;i++) //iterating 100 times
{
//rand() generates raandom number we used %6 to generate random number between 0 to 5 and added one to get number in die's range(1 to 6)
int value_die1 = 1+(rand()%6);
int value_die2 = 1+(rand()%6);
q1.push(value_die1);
q2.push(value_die2);
}
int ans=0;//will tel number of apir which adds up to 7 or doubles
while(!q1.empty())//as size of both q1 and q2 same run lopp til any of them is no empty;
{
int value1 = q1.front();
q1.pop();
int value2 = q2.front();
q2.pop();
if(value1==value2) //both number at dies are same(doubles)
ans++;
if((value1+value2)==7)
ans++;
}
cout<<ans;
}