Skip to content

Instantly share code, notes, and snippets.

@eburke
Created March 15, 2016 01:42
Show Gist options
  • Save eburke/7e15c11eb8898c895d71 to your computer and use it in GitHub Desktop.
Save eburke/7e15c11eb8898c895d71 to your computer and use it in GitHub Desktop.
Unexpected coin toss probability
import java.util.Random;
/*
If Alice tosses a coin until she sees a head followed by a tail, and Bob tosses a coin until he
sees two heads in a row, then on average, Alice will require four tosses while Bob will require
six tosses (try this at home!), even though head-tail and head-head have an equal chance of
appearing after two coin tosses.
https://www.quantamagazine.org/20160313-mathematicians-discover-prime-conspiracy/
*/
public class Main {
public static final int NUM_SIMULATIONS = 100000;
public static final boolean HEAD = true;
public static final boolean TAIL = false;
private static final Random rand = new Random();
public static void main(String[] args) {
long totalAlice = 0;
long totalBob = 0;
for (int i = 0; i < NUM_SIMULATIONS; i++) {
totalAlice += simulateUntil(HEAD, TAIL);
totalBob += simulateUntil(HEAD, HEAD);
}
System.out.println("Average for Alice = " + ((double) totalAlice / NUM_SIMULATIONS));
System.out.println("Average for Bob = " + ((double) totalBob / NUM_SIMULATIONS));
}
private static int simulateUntil(boolean toss1, boolean toss2) {
int numTosses = 2;
boolean prev = rand.nextBoolean();
boolean cur = rand.nextBoolean();
while (!(prev == toss1 && cur == toss2)) {
prev = cur;
cur = rand.nextBoolean();
numTosses++;
}
return numTosses;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment