From: Niklas Frykholm Date: 2001-10-09T06:17:38+09:00 Subject: [ruby-talk:22262] Re: [Newbie] Switching from Perl : suffling On Tue, Oct 09, 2001 at 04:58:24AM +0900, Dave Thomas wrote: > How about something like > > class Array > def shuffle > each_index {|i| o = rand(size); self[i], self[o] = self[o], self[i] } > end > end That code in fact results in a slightly biased shuffle. The easiest way to realize that is probably this: Suppose that we have an array with 3 items, then there are 3! = 6 different shuffles. Your code can take one of 3*3*3 = 27 different paths. Each path ends in a particular shuffle. But since 6 does not divide 27, the shuffles cannot be equally likely. Or try count = Hash.new(0) 100000.times {a = [1,2,3]; a.shuffle; count[a]+=1} p count Here is a fixed shuffle class Array def shuffle! each_index {|i| o=rand(size-i); self[i], self[i+o] = \ self[i+o], self[i]} end end // Niklas