Skip to content

Instantly share code, notes, and snippets.

@toothrot
Created July 21, 2010 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toothrot/484005 to your computer and use it in GitHub Desktop.
Save toothrot/484005 to your computer and use it in GitHub Desktop.
shuffling arrays for 1.8.6
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;
}
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
# 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 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