Hello everyone!
I am writing a program for the birthday paradox that runs trials 10,000 times. I want to show that when N people are in a room, there is a 50% chance that there will be a duplicate birthday.
I want to create an empty set, then add to it random birthdays. Then I want to see if there are any duplicates, and if there are, I want to calculate the percentage of sets that have duplicates. I then want to stop the program when N people exceeds 365 or when the percentage hits 50%.

However, I am not sure where my code is going wrong or how to implement the block of code that makes it stop when the target percentage is reached, or when N = 23. Therefore, I have not implemented that aspect.

Could someone tell me if the logic of the code is correct and how to implement it stopping?

  import java.util.HashSet;
    import java.util.Random;

    public class birthdayProblem {
        public static void main(String[] args) {

            //repeat trial for increasing values of N starting at 2
            int yearLength = 365;
            double targetPercentage = 0.5;
            int duplicate = 0;
            int people = 2;
            int i = 0;
            int totalSet = 0;
            while (i <= 10000) {
                for (int j = 0; j <= yearLength; j++) {
                    Random birthdays = new Random();
                    HashSet<Integer> hash = new HashSet<>();

                    for (i = 0; i < 365; i++)
                        hash.add(1 + birthdays.nextInt(365));
                    birthdays.nextInt(365);
                    if (hash.contains(duplicate)) {
                        duplicate++;
                        break;
                    } else {
                        hash.add(duplicate);
                        totalSet++;
                        people++;
                    }

                }
                double average = (double) duplicate / totalSet;
                System.out.println("N value is " + people + " and the percentage is " + average);
            }


        }
    }

This is marked as "solved". Is that right?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.