In: Computer Science
The birthday paradox says that the probability (chance) that two people in a room will have the same birthday is more than half as long as n, the number of people in the room, is more than or equal to 23. This property is not really a paradox, but many people find it surprising. Write a Java program that generates 10 sets of 23 valid birthdays (ignore leap years). Check how many times the Birthday Paradox occurs and keep count of it. ONLY using arraylist please in java
Thanks for the question. Here is the completed code for this problem. Have used ArrayList only as you requested and not arrays. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks =========================================================================== import java.util.ArrayList; import java.util.Random; public class BirthdayParadox { public static void main(String[] args) { int countOfBParadox = 0; Random random = new Random(); int EXPERIMENTS = 10; // the number of sets we want to perform the experiement for (int experiement = 1; experiement <= EXPERIMENTS; experiement++) { // create an arraylist of integer // there will be 366 indices each representing a day in a year // the first index is not considered, that is index 0 is left out // index 1 will represent day 1 ie. January 1st, index 364 represent 30th December like wise //index 365 represent 31st December like wise ArrayList<Integer> birthdays = new ArrayList<Integer>(); for (int blank = 1; blank <= 366; blank++) birthdays.add(0); for (int person = 1; person <= 23; person++) { // birthdate can be any day in the 365 days of a year int birthDate = random.nextInt(365) + 1; // increment the value by 1, so if there was already a birthday // previously at this date it will increment to 2 birthdays.set(birthDate, birthdays.get(birthDate) + 1); // check the value is 2, then the birthday is repeating if (birthdays.get(birthDate) == 2) { System.out.println("Same birthday found."); countOfBParadox++; break; } } } System.out.println("We have found " + countOfBParadox + " times when the birthday was repeated " + " in a set of " + EXPERIMENTS); System.out.println("Probability (%): "+countOfBParadox*1.0/EXPERIMENTS); } }
=================================================================