Skip to content

Instantly share code, notes, and snippets.

@krohrbaugh
Created April 21, 2010 15:05
Show Gist options
  • Save krohrbaugh/373923 to your computer and use it in GitHub Desktop.
Save krohrbaugh/373923 to your computer and use it in GitHub Desktop.
Shuffling an array in Ruby, based on the Array#shuffle! implementation in ruby-1.9
=begin
This is the actual C-based implementation of Array#shuffle! in ruby-1.9:
/*
* call-seq:
* array.shuffle! -> array
*
* Shuffles elements in _self_ in place.
*/
static VALUE
rb_ary_shuffle_bang(VALUE ary)
{
long i = RARRAY_LEN(ary);
rb_ary_modify(ary);
while (i) {
long j = rb_genrand_real()*i;
VALUE tmp = RARRAY_PTR(ary)[--i];
RARRAY_PTR(ary)[i] = RARRAY_PTR(ary)[j];
RARRAY_PTR(ary)[j] = tmp;
}
return ary;
}
=end
# Non-destructive shuffle
def shuffle(array)
shuffled = array.dup
shuffle!(shuffled)
end
# Here's a basic translation of the C into Ruby
def shuffle!(array)
i = array.size
while i > 0 do
random_index = rand(i)
i -= 1
temp_val = array[i]
array[i] = array[random_index]
array[random_index] = temp_val
end
array
end
# Let's see if it works
v = [1]
w = []
x = [1,2,3,4,5,6]
y = ["a","b","c","d"]
z = ["pretty","cool","right"]
puts "#{v} => #{shuffle(v)}"
puts "#{w} => #{shuffle(w)}"
puts "#{x} => #{shuffle(x)}"
puts "#{y} => #{shuffle(y)}"
puts "#{z} => #{shuffle(z)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment