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

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);
    }

Step by Step Solution

3.41 Rating (154 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

It seems like the issue is in your averagePairs method You are overwriting the value of pairs in eac... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!