Below is the syntax highlighted version of DiscreteDistribution.java.
/******************************************************************* * Login, etc: * Compile: javac DiscreteDistribution.java * Execute: java DiscreteDistribution freq0 freq1 freq2 . . . * * Reads in an array of N frequency counts from the command line, * and prints out i with probability proportional to the ith * frequency count. * * // six equally likely events * % java DiscreteDistribution 1 1 1 1 1 1 * 3 * * % java DiscreteDistribution 1 1 1 1 1 1 * 0 * * // six events, one 3x more likely than the others * % java DiscreteDistribution 1 1 1 1 1 3 * 5 * * % java DiscreteDistribution 1 1 1 1 1 3 * 2 * * % java DiscreteDistribution 1 1 1 1 1 3 * 5 Web Exercise 1.4.2 *************************************************************************/ public class DiscreteDistribution { public static void main(String[] args) { // read in N frequencies. store in integer array. int N = __________________________; ____________[] freq = __________ int[___]; for (_____________________; __________________; __________) { freq[_____] = Integer.parseInt(__________________); } // compute total count of all frequencies int total = ______; for (int i = 0; i < N; i++) { total += __________________________________; } // generate random integer with probability proportional to frequency int r = (int) (total * Math.random()); // integer in [0, total) int sum = 0; int event = -1; for (int i = 0; i < N && sum <= r; i++) { sum += freq[i]; event = i; } System.out.println(event); } }