From: Rick DeNatale Date: 2007-04-30T11:45:36+09:00 Subject: Re: sorting by rand? On 4/29/07, Peter Seebach wrote: > In message <40D2708E-0D0C-42E4-82B3-E31D93481880@mac.com>, Gary Wright writes: > > > >On Apr 29, 2007, at 10:01 PM, Peter Seebach wrote: > >> So, two vaguely related questions: > >> 1. Is there a reasonably sane way to do this, should I ever find > >> myself wanting one? > > > >Short answer: array.sort_by { rand } > > > >Longer answer: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby- > >talk/168963 > > Well, okay. It works in practice. Is it guaranteed to work, and is > it actually reasonable to expect the output to be randomly shuffled? See my longer explanation of sort_by which crossed in the e-mail. > Just for comparison, I tried: > > l = a.length > a.each_index { |x| a[x] = a[rand(l)] } > > I'm pretty sure I got the generic shuffle algorithm right (Knuth FTW), > and if so, it produces quality random results in about 1/4 the time. Looks suspicious to me, you are replacing each element of x in turn with a randomly selected element, which means that you are likely to end up with a different set of elements in the end. One of the requirements of shuffling an array would seem to be that shuffle(a).sort == a.sort Something like: a.each_index {|x| y=rand; a[x], a[y] = a[y], a[x]} would seem to be a better approach, but a.sort_by {rand} does the same thing more concisely. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/