How Many People Have To Be In A Room for Two People To Share A Birthday?
How many people have to be in a room for two of the people to share a birthday? This program addresses this question. You'll do a simulation of people entering a large room, one by one, until two of them have the same birthday.
It probably makes sense to generate random birthdays as integers between 1 and 365. (We're assuming it's not a leap year.) This can be done in the method 'addPeopleToARoom'.
We would like to express each birthday in the usual way, like "March 23" or "September 4". The method 'expressAsDate' does this conversion. You'll notice the class 'Month' at the bottom of the file. It has two instance variables, for the month and the date. My approach: I chose to convert from a number (32) to a day ("February 1") by setting up (in the Birthday constructor) an array of 12 Month objects, for January, February, etc. In 'expressAsDate()' I set up a while loop to do the conversion. I used an integer 'cumulativeDays' to keep track of how many days had passed as I stepped through the months inside the while loop, looking for the correct month. Once I found the correct month, I calculated the date within that month. You should feel free to find your own approach for doing this conversion.
People enter the room one by one in the method 'addPeopleToARoom'. Once you generate the integer between 1 and 365 that will be their birthday, you could store the integer in an ArrayList of Integer objects. An ArrayList has a 'contains' method that checks whether a given Integer is stored in the ArrayList. You should print to the screen each time a person enters the room.
You stop the loop and print your results once two people in the room share a birthday.
Here is output from one run of the program:
Here you want to run the simulation many times. The goal is to figure out these statistics:
- minimum number of people
Each time you run a simulation, print to an output file just the number of people in the room when a shared birthday occurs. Try running 10,000 simulations. When the program is done, open your output file in Excel and calculate the statistics listed above. An ArrayList has a 'clear' method that deletes the current content.
Allow your user to run as many simulations as they choose, as seen below:
You can download Birthday.java to use as a starting point in writing your program.