# Duplicate Birthday's program

• 12-05-2011, 02:10 AM
tronez
Duplicate Birthday's program
Hi

Im very new to java and trying to make a simple java program which will work out the chances of two people sharing the same birthday in say a class of 40 people. Using the monte Carlo method the above senerio will be simulated 10,000 times. Below is the code I have already written

Code:

```public class birthday {     public static void main(String[] args)     {         long experiments = 10000;         long bdaycount = 0;         int bday1, bday2;             for(long i = 0; i < experiments; i++) {                     for(int j = 0; j < 20; j++) {                       bday1 = probability();       bday2 = probability();                 if(bday1 == bday2) {             bdaycount++;                         break;                     }               } }     System.out.println("prob is: " + ((double)bdaycount / (double)experiments)); }     public static int probability()     {         double x = Math.random();         x = 1.0 + (x * 365);         int outcome = (int)Math.floor(x);                 return outcome;             }         }```
But I quickly figured at that all this is doing is getting two birthdays at a time and comparing those instead of the entire class of 40. I thought that it may be possible to store the values in an array but im not sure. So i made the following array and a for loop to generate the different random bithdays, however i now dont no how I can check this array to see if 2 or more of the same values are present.

Code:

```int myarray[] = new int[40];                 for(int i = 0; i < myarray.length; i++){             myarray[i] = (int)(Math.random() * 365);                     }```

Any help will be appreciated.

Thanks
• 12-05-2011, 02:21 AM
pbrockway2
Re: Duplicate Birthday's program
Check if the zero-th entry is equal to any entry after that, check if entry 1 is equal to entry 2->. etc etc. A double (nested) loop should do it.

Code:

```for(each person in array) {     check for(everyone after them in the array) }```
But if you spend a bit more space you get back a lot of speed. Make your array 365 long, not 40. Then for each person in the class add one at the position of their birthday. Now all you have to do is search the "calendar" array for any entry >1. You won't know who the birthday pair are, but that doesn't matter for your problem.

 thinking a bit, you don't even have to do this much. In particular you don't need to assign everyone a birthday: just assign birthdays and check them against the calendar array. You can stop as soon as you've found a person with a birthday whose slot is already taken. (now the array can be boolean[365])
• 12-05-2011, 04:29 AM
Junky
Re: Duplicate Birthday's program