Created
February 25, 2012 16:13
-
-
Save bkeepers/1909309 to your computer and use it in GitHub Desktop.
Ruby implementation of swap algorithm from http://beust.com/weblog/2012/02/20/various-ways-to-get-randomness-wrong/
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
# puts (1..100).to_a.shuffle.inspect | |
class Array | |
def shuffle | |
size.downto(1) { |n| swap(n - 1, rand(n)) } | |
self | |
end | |
def swap(x, y) | |
self[x], self[y] = self[y], self[x] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI, this doesn't create an even distribution. Check out the blog post to find out why.