Created
February 7, 2012 00:51
-
-
Save kimyoutora/1756275 to your computer and use it in GitHub Desktop.
Shuffle cards in place
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
# randomly shuffle cards in-place | |
# Fisher-Yates Shuffle | |
# Use the back of the array for storing the | |
# randomly picked card and move your way to the front | |
class Array | |
def shuffle | |
length = self.size | |
array = self.dup | |
(length - 1).step(0, -1).each do |i| | |
random_index = rand(i+1) | |
tmp = array[i] | |
array[i] = array[random_index] | |
array[random_index] = tmp | |
end | |
array | |
end | |
end | |
a = (0...52).to_a | |
puts a.inspect | |
puts a.shuffle.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment