Skip to content

Instantly share code, notes, and snippets.

@morfioce
Last active August 21, 2017 07:36
Show Gist options
  • Save morfioce/5df44ff59b6abc041f6737dcefabbbaa to your computer and use it in GitHub Desktop.
Save morfioce/5df44ff59b6abc041f6737dcefabbbaa to your computer and use it in GitHub Desktop.
Shuffle fairness tester
def fact(n):
return 1 if n == 1 else n * fact(n-1)
def test_shufller(shuffler, items, n=100000):
counts = {}
for _ in range(n):
array = list(items)
shuffler(array)
p = ''.join(array)
counts[p] = counts.get(p, 0) + 1
# exptected counts
expected = n / fact(len(deck))
ok = all([0.99 <= val/expected <= 1.1 for val in counts.values()])
if ok:
print('fairly random: yep')
else:
print('fairly random: nope')
print('shuffler: ', shuffler.__name__)
print('input: ', array)
print('permutations\'s distribution', [(key,val*100/n) for key, val in counts.items()])
print('------------------------------------')
test_input = 'abc'
test_shufller(naive_shuffler, test_input)
test_shufller(knuth_shuffler, test_input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment