Created
July 30, 2013 21:26
-
-
Save danslimmon/6117144 to your computer and use it in GitHub Desktop.
Sorting by a random comparison function is a crappy way to shuffle.
This file contains hidden or 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
# Sort [1,2,3,4] with a cmp function that returns -1, 0, or 1 with equal probability. | |
# Do it 10^5 times. | |
h={1:0,2:0,3:0,4:0} | |
for i in range(99999): | |
a = sorted([1,2,3,4], | |
lambda a, b: random.sample([-1,0,1], 1)[0]) | |
h[a[0]] += 1 | |
h | |
# => {1: 60443, 2: 17374, 3: 10990, 4: 11192} | |
# The first element of `a` was `1` 60% of the time! | |
# Even if the cmp function only returns -1 or 1, it's still bad: | |
h={1:0,2:0,3:0,4:0} | |
for i in range(99999): | |
a = sorted([1,2,3,4], | |
lambda a, b: random.sample([-1,1], 1)[0]) | |
h[a[0]] += 1 | |
h | |
# => {1: 36170, 2: 13965, 3: 18735, 4: 31129} | |
# Now we get a decent number of 4's, but still nowhere near uniform. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment