Skip to content

Instantly share code, notes, and snippets.

@domino14
Created May 8, 2018 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domino14/de4c8f821e2b5cd37430d2224e40ee54 to your computer and use it in GitHub Desktop.
Save domino14/de4c8f821e2b5cd37430d2224e40ee54 to your computer and use it in GitHub Desktop.
monte carlo tile drawer
import random
import sys
def to_freqs(tiles):
""" Convert tiles to freq dictionary. """
f = {}
for t in tiles:
if t not in f:
f[t] = 1
else:
f[t] += 1
return f
def tiles_in_rack(tiles, rack):
"""
Check if tiles are in rack.
>>> tiles_in_rack('ABC', 'ABC')
True
>>> tiles_in_rack('ABC', 'AB')
False
>>> tiles_in_rack('BOOT', 'BOOOTTOB')
True
>>> tiles_in_rack('BOOTBB', 'BOOOTTOB')
False
>>> tiles_in_rack('A', 'BCDEFG')
False
"""
rfreq = to_freqs(rack)
for t in tiles:
if t not in rfreq or rfreq[t] == 0:
return False
rfreq[t] -= 1
return True
def simmer(pool, desired_rack, num_drawing):
iterations = 0
successes = 0
while True:
plist = list(pool)
random.shuffle(plist)
if tiles_in_rack(desired_rack, plist[:num_drawing]):
successes += 1
iterations += 1
if iterations % 10000 == 0:
print('Success rate: {}, iterations: {}'.format(
successes/iterations, iterations))
if __name__ == '__main__':
pool = sys.argv[1]
desired_rack = sys.argv[2]
num_drawing = int(sys.argv[3])
simmer(pool, desired_rack, num_drawing)
@domino14
Copy link
Author

domino14 commented May 9, 2018

This can be used like:

python simmer.py <pool> <tiles> <number-being-drawn>

For example,

python simmer.py DEEEIINOQR? DEQ? 6

This gives you the probability of drawing at least DEQ? on a 6-tile draw from the pool DEEEIINOQR? by using the Monte Carlo method. An analytical solution is a bit more complicated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment