/** * @author ezgi * */ public class CoinFlip { /** * @return true with .5 probability */ public static boolean heads(){ return Math.random() < 0.5; } /** * @param args[0] number of coin flips in one trial (N) * @param args[1] number of trials (M) */ public static void main(String[] args){ /* * i and j are indexing variables * cnt keeps track of number of heads in one trial */ int i, j, cnt; int N = Integer.parseInt(args[0]); int M = Integer.parseInt(args[1]); /* * hist: histogram of head counts * hist[j] is the count of how many of the M trials got j heads */ int[] hist = new int[N+1]; for (j = 0; j <= N; j++) hist[j] = 0; /* * Flip the coin and count the number of heads. * Increment the corresponding histogram bin after each trial. */ for (i = 0; i < M; i++, hist[cnt]++) for (cnt = 0, j = 0; j <= N; j++) if (heads()) cnt++; /* * Print the histogram * With big enough number of trials, it should be a normal distribution */ for (j = 0; j <= N; j++) { System.out.print(j); if (hist[j] == 0) System.out.print("."); for (i = 0; i < hist[j]; i+=1) System.out.print("*"); System.out.println(); } } }