/************************************************************************* * Compilation: javac Birthday.java * Execution: java Birthday T N * * Computes the number of people (by simulation) that must enter a room * until two of them share a birthday. Assumes birthdays a uniform * and independent from 0 to N-1. Repeats the experiment T times and * prints the average * * % java Birthday 100000 365 * Average = 24.65394 * *************************************************************************/ public class Birthday { public static void main(String[] args) { int T = Integer.parseInt(args[0]); // number of trials int N = Integer.parseInt(args[1]); // number of days int count = 0; // total number of people for (int t = 0; t < T; t++) { boolean[] days = new boolean[N]; // auto-initialized to false while (true) { count++; int d = (int) (N * Math.random()); // integer between 0 and N-1 if (days[d]) break; days[d] = true; } } System.out.println("Average = " + 1.0 * count / T); } }