Created
July 21, 2010 03:19
-
-
Save toothrot/484005 to your computer and use it in GitHub Desktop.
shuffling arrays for 1.8.6
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
static VALUE | |
rb_ary_shuffle_bang(ary) | |
VALUE ary; | |
{ | |
long i = RARRAY(ary)->len; | |
rb_ary_modify(ary); | |
while (i) { | |
long j = rb_genrand_real()*i; | |
VALUE tmp = RARRAY(ary)->ptr[--i]; | |
RARRAY(ary)->ptr[i] = RARRAY(ary)->ptr[j]; | |
RARRAY(ary)->ptr[j] = tmp; | |
} | |
return ary; | |
} |
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
class Array | |
def shuffle! | |
i = size | |
while(i>0) | |
j = rand() * i | |
tmp = self[(i-=1)] | |
self[i] = self[j] | |
self[j] = tmp | |
end | |
self | |
end | |
end | |
# I think I like this one the best: | |
class Array | |
def shuffle! | |
size.times do |i| | |
j = i + rand(size - i) | |
self[i], self[j] = self[j], self[i] | |
end | |
self | |
end | |
end | |
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
# It works, and it's harder to read to boot - @jaknowlden | |
class Array | |
def shuffle! | |
i = size | |
while(i>0) | |
j,i = rand() * i, (i-1) | |
self[i], self[j] = self[j], self[i] | |
end | |
self | |
end | |
end |
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
#this takes advantage of rubinius' Tuple class. Left here as an example. | |
# Shuffles elements in self in place. | |
def shuffle! | |
size.times do |i| | |
r = i + Kernel.rand(size - i) | |
@tuple.swap(i,r) | |
end | |
self | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment