Skip to content

Instantly share code, notes, and snippets.

Created May 28, 2012 04:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/2817224 to your computer and use it in GitHub Desktop.
Array shuffle test examples
import random
def testShuffle(shuffle, trials):
baseList = [1, 2, 3, 4]
counts = {}
for i in range(trials):
shuffleList = shuffle(baseList[:])
key = str(shuffleList)
if not (key in counts):
counts[key] = 1
else:
counts[key] += 1
sortedKeys = counts.keys()
sortedKeys.sort()
for key in sortedKeys:
print key, "\t", round(counts[key] / float(trials), 4)
def fisher_yates(shuffleList):
for i in range(len(shuffleList)):
index = random.randint(0, i)
item = shuffleList[i]
shuffleList[i] = shuffleList[index]
shuffleList[index] = item
return shuffleList
def naive(shuffleList):
listLength = len(shuffleList)
for i in range(listLength):
index = random.randint(0, listLength-1)
item = shuffleList[i]
shuffleList[i] = shuffleList[index]
shuffleList[index] = item
return shuffleList
def terrible(shuffleList):
for i in range(len(shuffleList)):
index = random.randint(0, 3)
item = shuffleList[index]
shuffleList.pop(index)
shuffleList.append(item)
return shuffleList
print "Fisher-Yates"
testShuffle(fisher_yates, 500000)
print "Naive"
testShuffle(naive, 500000)
print "Terrible"
testShuffle(terrible, 500000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment