Category Archives: benchmarking

A simple shuffle that proved not so simple after all

Yesterday I found following snippet of Ruby magic to shuffle an array:

class Array 
  def shuffle 
    sort { rand(3) - 1 } 
  end 
end                                                      

arr = (1..10).to_a 
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]                                                     

arr.shuffle 
# => [1, 8, 6, 10, 9, 3, 7, 2, 5, 4]                                                     

arr.shuffle 
# => [3, 7, 10, 4, 5, 8, 2, 6, 9, 1]

There is one thing wrong with it, but the original site no longer permits commenting on this entry, so I thought I’d share my thoughts here.
Continue reading

Advertisements