Created
December 19, 2018 00:31
-
-
Save iconjack/871a67e2e302af595684880ae9d64dfc to your computer and use it in GitHub Desktop.
Compute probability of winning High Rollers dice game.
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
from fractions import Fraction | |
from functools import lru_cache | |
from itertools import * | |
def powerset(S): | |
return chain.from_iterable(combinations(S, r) for r in range(len(S)+1)) | |
@lru_cache(maxsize=512) | |
def p(S): # S is a frozenset so it can be cached | |
if len(S) == 0: | |
return Fraction(1) | |
total = Fraction(0) | |
for d1 in [1,2,3,4,5,6]: | |
for d2 in [1,2,3,4,5,6]: | |
roll = d1 + d2 | |
moves = [set(T) for T in powerset(S) if sum(T) == roll] | |
if len(moves) == 0: | |
score, move = 0, None | |
else: | |
score, move = max(zip(map(lambda T: p(S-T), moves), moves)) | |
total += score * Fraction(1,36) | |
return total | |
prob = p(frozenset([1,2,3,4,5,6,7,8,9])) | |
print("exact value: ", prob) | |
print(" as a float: ", float(prob)) | |
print("1 chance in: ", 1/float(prob)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment