Skip to content

Instantly share code, notes, and snippets.

@eggsyntax
Last active December 4, 2023 20:01
Show Gist options
  • Save eggsyntax/c6363119a39d88ff3eee5a90b3499b06 to your computer and use it in GitHub Desktop.
Save eggsyntax/c6363119a39d88ff3eee5a90b3499b06 to your computer and use it in GitHub Desktop.
# https://gilkalai.wordpress.com/2017/09/07/tyi-30-expected-number-of-dice-throws/
from pprint import pprint
import random
def toss():
"Throw a die. Return the result if the result is even; otherwise None"
n = random.randint(1,6)
if n % 2: # odd
return None
return n
def toss_until_6():
throws = []
n = -1
while n != 6:
n = toss()
if n:
throws.append(n)
else: # invalid run (gave an odd number)
return None
return throws
def get_n_valid_runs(n: int):
runs = []
while len(runs) < n:
run = toss_until_6()
if run:
runs.append(run)
return runs
def get_ave_length(n_good_runs: int, num_sides=6):
"""Ave length approaches the correct limit as n_good_runs increases.
1000000 is enough to be accurate, and runs in a few seconds."""
runs = get_n_valid_runs(n_good_runs)
run_lengths = [len(run) for run in runs]
return sum(run_lengths) / len(runs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment