Created
May 8, 2018 23:29
-
-
Save domino14/de4c8f821e2b5cd37430d2224e40ee54 to your computer and use it in GitHub Desktop.
monte carlo tile drawer
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 poolDEEEIINOQR?
by using the Monte Carlo method. An analytical solution is a bit more complicated.