monte carlo birthday problem java
#include <stdio.h> // print #include <stdlib.h> <span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span> // rand #include <time.h> // time // This program will determine the percentage of times that two or more people share a birthday // It will iterate from 2 people to 'maxNumPeople' and in each version it will do 'numSimulations' simulations int main() { int numPeople; // Number of people in this version int maxNumPeople = 100; // Maximum number of people to test with. Must be less than 100 int simNum; // Simulation number long numSimulations = 1000000; // Number of simulations to try in this version long numMatches; // Keeps track of number of matches in this version int birthdays[100]; int i, j; // Incrementers fin for loop int isMatch; // Flag for later // Seed RNG with time to get unique results each time srand(time(NULL)); // Iterate over the number of people in this version for(numPeople=2; numPeople<maxNumPeople; numPeople++) { // Reset the number of matchs for this version numMatches = 0; // Iterate the number of simulations in this version for(simNum = 0; simNum<numSimulations; simNum++) { for(i=0; i<numPeople; i++) { // Give each bday a value, in this case a day from 1 to 365 inclusive // rand()%365 returns from 0 to 364 so we add 1 to it // We could just as easily leave the 1 off and it would still work, but doesn't hurt birthdays[i] = 1 + rand()%365; } // Reset the isMatch flag isMatch=0; // Determine if there is a match // Note that this is a very inefficent way to do compare for(i=0; i<numPeople-1; i++) { for(j=i+1; j<span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span><numPeople; j++) { // Compare i and j birthdays if(birthdays[i] == birthdays[j]) { // If they match, then set flag and break isMatch=1; break; } } // This flag is to break out of the outer for loop if a mathc is already found if(isMatch==1) { break; } } // If the match flag was set, increment the number of matches if(isMatch==1) numMatches++; } // Print out the numPeople in this version and the percentage of times there wa a match printf("%d, %f \n", numPeople, 100.0*numMatches/numSimulations); } return 0; }