After completing the method run the following experiments: Perform 1,000,000 experiments with 365 days per year and
Question:
After completing the method run the following experiments:
Perform 1,000,000 experiments with 365 days per year and 182 people per experiment . What is the average number of pairs of people with shared birthdays?
My code looks like this, and they generate a very wired answer. Find out what's wrong with them.
public static int sharedBirthdays(int numPeople, int numDaysInYear) {
// check preconditions
if (numPeople <= 0 || numDaysInYear <= 0) {
throw new IllegalArgumentException("Violation of precondition: " +
"sharedBirthdays. both parameters must be greater than 0. " +
"numPeople: " + numPeople +
", numDaysInYear: " + numDaysInYear);
}
int[] birthdays = new int[numPeople];
Random random = new Random();
if (numPeople == 1) {
return 0;
} else {
for (int i = 0; i < numPeople; i++) {
birthdays[i] = random.nextInt(numDaysInYear);
}
int numPairs = 0;
for (int i = 0; i < numPeople; i++) {
for (int j = i + 1; j < numPeople; j++) {
if (birthdays[i] == birthdays[j]) {
numPairs++;
}
}
}
return numPairs;
}
}
public static void averagePairs(int numPeople, int numDaysInYear, int trails) {
int pairs = 0;
for (int i = 0; i < trails; i++) {
pairs = sharedBirthdays(numPeople,numDaysInYear);
}
double average = (double) pairs / trails;
System.out.println("The average pais is" + average);
}
Financial Management for Public Health and Not for Profit Organizations
ISBN: 978-0132805667
4th edition
Authors: Steven A. Finkler, Thad Calabrese