Problem prompt
Birthday problem. Suppose that people enter a room one at a time. How people must enter until two share a birthday? Counterintuitively, after 23 people enter the room, there is approximately a 50–50 chance that two share a birthday. This phenomenon is known as the birthday problem or birthday paradox. Write a program Birthday.java that takes two integer command-line arguments n and trials and performs the following experiment, trials times:
Choose a birthday for the next person, uniformly at random between 0 and n−1. Have that person enter the room. If that person shares a birthday with someone else in the room, stop; otherwise repeat. In each experiment, count the number of people that enter the room. Print a table that summarizes the results (the count i, the number of times that exactly i people enter the room, and the fraction of times that i or fewer people enter the room) for each possible value of i from 1 until the fraction reaches (or exceeds) 50%. sampling from a discrete distribution
Example of how output should look
And here is my code. I keep outputting only one line, (1 999999.0 0.999999) and CANNOT figure out what is wrong.
public class Birthday {
public static void main (String[]args)
{
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
int[] times = new int[n];
boolean [] found = new boolean[n-1];
for (int i=0; i<trials; i++)
{
for (int j=0; j<n; j++)
{
int rand = (int) Math.random() * n;
if (!found[rand])
{
found[rand] = true;
}
else
{
times[j]++;
break;
}
}
}
int m = 0;
double frac = 0;
double count=0;
while (frac < 0.5)
{
count += times[m];
frac = count/trials;
System.out.println(m+1 + " " +count + " "+ frac);
m++;
}
}
}
Please help me, I am getting desperate lol! Happy MLK day everyone.
This line is always zero because the type casting operator has higher precedence than multiplication:
You need to use parentheses: