Skip to content

Instantly share code, notes, and snippets.

@LaurentMazare
Created February 24, 2025 12:37
Show Gist options
  • Select an option

  • Save LaurentMazare/959147be36c6b4cb654a3308fb0774a7 to your computer and use it in GitHub Desktop.

Select an option

Save LaurentMazare/959147be36c6b4cb654a3308fb0774a7 to your computer and use it in GitHub Desktop.
import itertools
NDICES = 8
def value(final_cfg, threshold=21):
v = sum([(i + 1) * n for (i, n) in enumerate(final_cfg)])
# At least one worm.
if final_cfg[5] > 0:
return int(v >= threshold)
else:
return 0.0
draws = []
for ndices in range(NDICES + 1):
ndraws = 6 ** ndices
_draws = {}
for draw in itertools.product(range(6), repeat=ndices):
cnts = [0] * 6
for d in draw:
cnts[d] += 1
cnts = tuple(cnts)
_draws[cnts] = _draws.get(cnts, 0) + 1
draws.append(_draws)
print(draws[0])
print(draws[1])
for d in draws:
print(sum(d.values()))
THRESHOLDS = [21]
for threshold in THRESHOLDS:
cache = {}
def dp(cfg):
key = tuple(cfg)
if key in cache:
return cache[key]
# Stop now
res = value(cfg, threshold=threshold)
dice_left = NDICES - sum(cfg)
can_continue = dice_left > 0 and sum([int(c > 0) for c in cfg]) < 6
if can_continue:
exp = 0.0
ndraws = 0
for (draw, draw_cnt) in draws[dice_left].items():
# select
tmp = 0
for picked_value in range(6):
# Cannot pick a value that was already picked.
if cfg[picked_value] > 0 or draw[picked_value] == 0:
continue
cfg[picked_value] += draw[picked_value]
_dp = dp(cfg)
tmp = max(tmp, _dp)
cfg[picked_value] -= draw[picked_value]
exp += draw_cnt * tmp
ndraws += draw_cnt
exp /= ndraws
res = max(res, exp)
cache[key] = res
return res
print(threshold, dp([0] * 6))
# Starting from 1 dice showing a 6
print(dp([0, 0, 0, 0, 0, 1]))
# Starting from 2 dices showing a 6
print(dp([0, 0, 0, 0, 0, 2]))
# Starting from 1 dice showing a 5
print(dp([0, 0, 0, 0, 1, 0]))
print(dp([0, 0, 0, 0, 2, 0]))
print(dp([0, 0, 0, 0, 3, 0]))
print(dp([0, 0, 0, 1, 0, 0]))
print(dp([0, 0, 0, 2, 0, 0]))
print(dp([0, 0, 0, 3, 0, 0]))
print(dp([0, 0, 0, 4, 0, 0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment