eden li <eden.li / gmail.com> writes:

> Why not just do a random sort instead?
>
>>> some_array = ['cat', 'dog', 'fun', 'zoo']
> => ['cat', 'dog', 'fun', 'zoo']
>>> some_array.sort { rand(3) - 1 }
> => ["zoo", "dog", "fun", "cat"]

That doesn't result in a good shuffle.  For example, if I shuffle
the array ["a", "b", "c"], I expect that "a" will be equally likely to
end up in any given position.  However:

irb(main):038:0> a = ('a'..'c').to_a
=> ["a", "b", "c"]
irb(main):039:0> d = Hash.new{|h,k|h[k]=0}
=> {}
irb(main):040:0> (1..27_000).each{ d[a.sort { rand(3) - 1 }.index("a")] += 1}
=> 1..27000
irb(main):041:0> p d
{0=>13940, 1=>2993, 2=>10067}
=> nil

That is, it's unlikely (only about a 1/9 chance) that "a" ends up in
the middle.

The suggestion to use sort_by { rand }, however, does give a good
shuffle.

-- 
s=%q(  Daniel Martin -- martin / snowplow.org
       puts "s=%q(#{s})",s.map{|i|i}[1]       )
       puts "s=%q(#{s})",s.map{|i|i}[1]