In: Computer Science
BACKGROUND: Given a group of 'n' people, the odds that at least two people have the same birthday are much higher than you would think.
PLEASE WRITE CODE IN C++
The program takes no input.
Assumptions:
1. There is an equal chance of birthday landing on any day of the year.
2. We are not considering a leap year (only 365 days)
The simulation will be run in the following manner:
1. For a group size 2, assign a random birthday to each member
2. If the birthdays are identical, keep a count.
3. Repeat 10,000 times.
4. Repeat the simulation for group sizes in the range [2,50]
NOTE: for groups larger than 2, you only need to find a single match in order for it to count.
Cpp Code:
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
//seeding the random number
srand((unsigned) time(0));
//array to keep the birthdays
int birthArr[50];
//for groups of 2 to 50
for (int i=2;i<=50;i++){
//matching birthdays found
int foundCount=0;
//10000 simulations
for(int j=1;j<=10000;j++){
//filling the array with 0 before simulation
fill_n(birthArr, 50, 0);
bool found =false;
//getting the birthday for i people
for(int k=0;k<i;k++){
//randomly getting the birthdays
birthArr[k] = 1 + (rand() % 365);
//checking if the birthday already exists in the array
for(int l=0;l<k;l++){
//checking for existence
if(birthArr[k] == birthArr[l]){
found = true;
break; //break if found
}
}
//breaking if found
if(found == true){
break;
}
}
if(found == true){
foundCount++; //incrementing the found count if found
}
}
//displaying the output
cout << "For n =" << i << " chance = "
<<(double)foundCount*100/10000 <<"%" <<
endl;
}
return 0;
}
Sample Output:
For n =2 chance = 0.22%
For n =3 chance = 0.82%
For n =4 chance = 1.54%
For n =5 chance = 2.61%
For n =6 chance = 3.92%
For n =7 chance = 5.42%
For n =8 chance = 7.37%
For n =9 chance = 9.85%
For n =10 chance = 12.4%
For n =11 chance = 13.71%
For n =12 chance = 15.68%
For n =13 chance = 19.34%
For n =14 chance = 22.05%
For n =15 chance = 25.95%
For n =16 chance = 28.49%
For n =17 chance = 31.97%
For n =18 chance = 35.08%
For n =19 chance = 38.6%
For n =20 chance = 40.31%
For n =21 chance = 45.06%
For n =22 chance = 47.82%
For n =23 chance = 50.22%
For n =24 chance = 53.43%
For n =25 chance = 56.14%
For n =26 chance = 58.85%
For n =27 chance = 63.48%
For n =28 chance = 65.01%
For n =29 chance = 68.15%
For n =30 chance = 70.82%
For n =31 chance = 74.33%
For n =32 chance = 75.78%
For n =33 chance = 77.16%
For n =34 chance = 79.03%
For n =35 chance = 81.3%
For n =36 chance = 83.44%
For n =37 chance = 84.95%
For n =38 chance = 86.25%
For n =39 chance = 87.57%
For n =40 chance = 89.77%
For n =41 chance = 90.15%
For n =42 chance = 90.95%
For n =43 chance = 91.93%
For n =44 chance = 92.81%
For n =45 chance = 94.02%
For n =46 chance = 94.6%
For n =47 chance = 95.31%
For n =48 chance = 96.03%
For n =49 chance = 96.93%
For n =50 chance = 97.12%