#984 – The Birthday Problem
November 28, 2013 2 Comments
To celebrate today’s Thanksgiving holiday in the United States, the post today is just a fun little code fragment for exploring the birthday problem. The idea of the birthday problem is to look at the probability of having at least one shared birthday in a group of n people.
Instead of calculating the actual probability of a collision, the code below empirically creates a group of people, assigns them birthdays, and then looks for shared birthdays. It does this 100,000 times and then reports what percentage of time there actually was a match.
static void Main(string[] args) { while (true) { Console.Write("Enter # people: "); int numPeople = int.Parse(Console.ReadLine()); const double NumTrials = 100000.0; int numBirthdayMatches = 0; double numUniqueBirthdaySum = 0; List<int> personBirthdays; Random rnd = new Random(); for (int trialNum = 1; trialNum <= NumTrials; trialNum++) { // Generate birthdays personBirthdays = new List<int>(numPeople); for (int personNum = 1; personNum <= numPeople; personNum++) personBirthdays.Add(rnd.Next(1, 366)); if (personBirthdays.Count != personBirthdays.Distinct().Count()) numBirthdayMatches++; numUniqueBirthdaySum += personBirthdays.Distinct().Count(); } double percentMatched = numBirthdayMatches / NumTrials * 100.0; double numUniquePerTrial = numUniqueBirthdaySum / NumTrials; Console.WriteLine(string.Format("For {0} people, there was at least one matching birthday {1}% of the time. Avg # unique birthdays={2}", numPeople, percentMatched, numUniquePerTrial)); } Console.ReadLine(); }