Skip to content

Instantly share code, notes, and snippets.

@joriki
Created December 5, 2019 20:57
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 joriki/e6e951041297bc547bbeef3f4919b828 to your computer and use it in GitHub Desktop.
Save joriki/e6e951041297bc547bbeef3f4919b828 to your computer and use it in GitHub Desktop.
Simulate the difference between the expected maximum length of a run of heads and the expected maximum length of a run of heads or tails; see https://math.stackexchange.com/questions/3464662.
import java.util.Random;
public class Question3464662 {
final static long ntrials = 10000000;
final static Random random = new Random ();
public static void main(String [] args) {
long headCounts = 0;
long bothCounts = 0;
for (long n = 0;n < ntrials;n++) {
int headCount = 0;
int tailCount = 0;
int maxHeadCount = 0;
int maxTailCount = 0;
for (int i = 0;i < 1000;i++) {
boolean heads = random.nextBoolean();
if (heads) {
headCount++;
tailCount = 0;
maxHeadCount = Math.max(maxHeadCount, headCount);
}
else {
tailCount++;
headCount = 0;
maxTailCount = Math.max(maxTailCount, tailCount);
}
}
headCounts += maxHeadCount;
bothCounts += Math.max(maxHeadCount, maxTailCount);
}
System.out.println(headCounts / (double) ntrials);
System.out.println(bothCounts / (double) ntrials);
System.out.println((bothCounts - headCounts) / (double) ntrials);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment