Skip to content

Instantly share code, notes, and snippets.

@davidhsv
Created June 9, 2016 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhsv/cd38ff8e3c2eb353099c61d52f5cde3d to your computer and use it in GitHub Desktop.
Save davidhsv/cd38ff8e3c2eb353099c61d52f5cde3d to your computer and use it in GitHub Desktop.
Coin Flip Test
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
// HT vs HH
// try to mess with this and see the result
boolean SHOULD_COUNT_CONSECUTIVE_FLIPS = false;
long occurrenciesHT = 0;
long totalWaitHT = 0;
int currentWaitHT = 0;
long occurrenciesHH = 0;
long totalWaitHH = 0;
int currentWaitHH = 0;
Boolean previousIsTails = false;
Boolean previousIsHeads = false;
SecureRandom instanceStrong = SecureRandom.getInstanceStrong();
for (int i = 0; i < 10000; i++) {
Boolean isTails = instanceStrong.nextBoolean();
Boolean isHeads = !isTails;
System.out.println(isTails ? "T" : "H");
currentWaitHT++;
currentWaitHH++;
// H T and ignore games with just 1 coin flip
if (previousIsHeads && isTails
&& (currentWaitHT > 1 || SHOULD_COUNT_CONSECUTIVE_FLIPS)) {
occurrenciesHT++;
totalWaitHT += currentWaitHT;
System.out.println("HT found!" + currentWaitHT);
currentWaitHT = 0;
}
// H H and ignore games with just 1 coin flip
if (previousIsHeads && isHeads
&& (currentWaitHH > 1 || SHOULD_COUNT_CONSECUTIVE_FLIPS)) {
occurrenciesHH++;
totalWaitHH += currentWaitHH;
System.out.println("HH found!" + currentWaitHH);
currentWaitHH = 0;
}
previousIsTails = isTails;
previousIsHeads = !previousIsTails;
}
System.out.println("occurrenciesHT=" + occurrenciesHT);
System.out.println("expectedWaitHT=" + ((totalWaitHT + 0.0) / occurrenciesHT));
System.out.println("occurrenciesHH=" + occurrenciesHH);
System.out.println("expectedWaitHH=" + ((totalWaitHH + 0.0) / occurrenciesHH));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment