Flip.java
Below is the syntax highlighted version of Flip.java
from §2.5 Arrays.
/*************************************************************************
* Compilation: javac Flip.java
* Execution: java Flip N
* Dependencies: StdDraw.java
*
* Each experiment consists of flipping N fair coins. Plots (in real
* time) a histogram of the number of times i of the N coins are heads.
*
* % java Flip 32
*
* % java Flip 64
*
* % java Flip 128
*
*************************************************************************/
public class Flip {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // number of coins to flip
int[] freq = new int[N+1]; // freq[i] = # times you get i heads
int freqMax = 500; // stop when one bucket has this many heads
StdDraw.create(600, 400);
StdDraw.setScale(0, 0, N, freqMax);
while (true) {
int heads = 0;
// flip N coins and tabulate the results
for (int j = 0; j < N; j++)
if (Math.random() < 0.5) heads++;
freq[heads]++;
// plot next box in histogram
StdDraw.go(heads, freq[heads]);
StdDraw.spot(0.5, 1.0);
StdDraw.pause(5);
// stop when it goes outside window
if (freq[heads] >= freqMax) break;
}
StdDraw.show();
}
}
Last updated: Thu Sep 23 16:38:21 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.