Skip to content

Instantly share code, notes, and snippets.

@joriki
Created April 2, 2020 10:50
Show Gist options
  • Save joriki/266413879aa228553a489de5070805e0 to your computer and use it in GitHub Desktop.
Save joriki/266413879aa228553a489de5070805e0 to your computer and use it in GitHub Desktop.
Simulate the expected average of dice rolls if the first roll is 1 and the trial ends when a roll repeats; see https://math.stackexchange.com/questions/3606037.
import java.util.Random;
public class Question3606037 {
final static long ntrials = 100000000;
final static Random random = new Random();
public static void main(String [] args) {
double total = 0;
for (long n = 0;n < ntrials;n++) {
double sum = 1;
int count = 1;
int last = 1;
for (;;) {
int roll = random.nextInt(6) + 1;
if (roll == last)
break;
sum += roll;
count++;
last = roll;
}
total += sum / count;
}
System.out.println(total / ntrials);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment