Created
June 9, 2016 18:29
-
-
Save davidhsv/1b69ce9ea1364fb0ea5d9ece8e32ee37 to your computer and use it in GitHub Desktop.
Consecutive Coin Flips - Numberphile - Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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