Title: Common Birthdays Example(using ints)
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Common Birthdays(using integer days of the year): Array Example

In the associated video, a program is developed in a bottom-up approach. In a bottom-up approach we recognize the lower level things needed and develop them first. At the end, we just make calls to the lower level routines we have created to finish the programming solution.

In the Common Birthday problem we are asking the question:

In a room of size N, what is the probability of 2 or more people having the same birthday.

We will take the simplest approach which is to assume that a birthdate is an integer between 1 and 365.

We create simulated random rooms of size N. We will then check to see if the simulated rooms have common birthdays. In the simulation, we will perform this experiment many times. By counting the number of times we have a common birthday we will compute a simulatred probability.

The code to solve this was developed on the video and the final program is shown below:

public class CommonBirthday {

    int[] createBirthdayRoom(int num)
    {
        int[] birthdays = new int[num];
        for (int i=0; i < num; i++)
        {
            birthdays[i] = (int)(1 + 365* Math.random());
        }
        return birthdays;
    }

    boolean commonBirthday(int[] birthdays)
    {
        for (int i=1; i < birthdays.length; i++)
        {
            for (int k = 0; k < i; k++)
            {
                if (birthdays[k] == birthdays[i])
                    return true;
            }
        }
        return false;
    }

    double simulate(int numSims, int roomSize)
    {
        int success = 0;
        for (int i=0; i < numSims; i++)
        {
            int[] br = createBirthdayRoom(roomSize);
            if (commonBirthday(br))
                success += 1;
        }
        return success/(double)numSims;
    }


    public static void main(String[] args) {
        CommonBirthday cb = new CommonBirthday();
        double prob = cb.simulate(100000, 24);

        System.out.println("Probability ="+ prob);

    }

}


Last Modified: September 29, 2013 6:47 PM