Tuesday, April 17, 2012

The consecutive heads problem

The consecutive heads problem (Chapter 6, exercise 2, page 214)
Heads. . . .
Heads. . . .
Heads. . . .
A weaker man might be moved to re-examine his faith, if in nothing
else at least in the law of probability.
—Tom Stoppard, Rosencrantz and Guildenstern are Dead, 1967
Write a program that simulates flipping a coin repeatedly and continues until three
consecutive heads are tossed. At that point, your program should display the total
number of coin flips that were made.

import java.util.Arrays;
import java.util.Random;

public class HeadsTails {
private static int[] results = { 0, 0, 0 };

/**
* @param args
*/
public static void main(String[] args) {
boolean flag = false;
Random r = new java.util.Random();

int c = 0;
while (!flag) {

if (r.nextInt() % 3 == 0) {
System.out.println("Heads");
results[0] = results[1];
results[1] = results[2];
results[2] = 1;

System.out.println(Arrays.toString(results));
if (checkheads())
break;
} else {
System.out.println("TAILS");
results[0] = results[1];
results[1] = results[2];
results[2] = 0;
System.out.println(Arrays.toString(results));
}
}
c++;
}

private static boolean checkheads() {
if (results[0] == 1 && results[1] == 1 && results[2] == 1)
return true;
else
return false;

}

}

No comments: