Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.