This is the syntax highlighted version of Birthday.java.
/*************************************************************************
* Compilation: javac Birthday.java
* Execution: java Birthday 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.
*
* % java Birthday 365
* 30
*
* % java Birthday 365
* 32
*
* % java Birthday 365
* 35
*
* % java Birthday 365
* 5
*
* % java Birthday 365
* 25
*
* % java Birthday 365
* 24
*
*************************************************************************/
public class Birthday {
public static void main(String[] args) {
int DAYS = Integer.parseInt(args[0]);
boolean[] days = new boolean[DAYS]; // auto-initialized to false
int count = 0; // number of people who have entered room
while (true) {
count++;
int d = (int) (DAYS * Math.random()); // integer between 0 and DAYS-1
if (days[d]) break;
days[d] = true;
}
System.out.println(count);
}
}
Last updated: Wed Feb 11 18:16:34 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.