Skip to content

Instantly share code, notes, and snippets.

View morfioce's full-sized avatar

Bouallagui Moncef morfioce

View GitHub Profile
@morfioce
morfioce / bad_shuffle.py
Last active August 21, 2017 07:13
An example of a biased shuffle
import random
def swap(array, i, j):
array[i], array[j] = array[j], array[i]
def shuffle(array):
n = len(array)
swapped = [False]*n
while not all(swapped):
i, j = random.randrange(n), random.randrange(n)
@morfioce
morfioce / good_shuffle.py
Last active August 21, 2017 06:16
Knuth's p shuffle algorithm.
import random
def swap(array, i, j):
array[i], array[j] = array[j], array[i]
def shuffle(array):
n = len(array)
for i in range(n-1):
swap(array, i, random.randrange(i,n))
@morfioce
morfioce / shuffle_simulation.py
Last active August 21, 2017 07:36
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

FWIW: I didn't produce the content present here. I've just copy-pasted it from somewhere over the Internet, but I cannot remember exactly the original source. I was also not able to find the author's name, so I cannot give him/her the proper credit.


Effective Engineer - Notes

What's an Effective Engineer?