#984 – The Birthday Problem

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

984-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #984 – The Birthday Problem

  1. Pingback: Dew Drop – December 2, 2013 (#1674) | Morning Dew

  2. Brian says:

    Very similar to the Monty Hall problem (http://en.wikipedia.org/wiki/Monty_Hall_problem). Another fun one that’s easy to implement and prove via code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: