Created
December 5, 2019 20:57
-
-
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.
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.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