On 12/4/05, Reinder Verlinde <reinder / verlinde.invalid> wrote:
> In article <dd3f270e4d20842e121bb970bc9a8386 / ruby-forum.com>,
>  Jim Weirich <jim-keyword-rforum.c88827 / weirichhouse.org> wrote:
>
> > hammed wrote:
> > > I'd like to sort collections randomly. This is what I tried first:
> > >
> > > my_array.sort { |a,b| rand(2) }
> >
> > my_array.sort_by { rand }
>
> A quick test seems to indicate that this works with the ruby 1.8.2
> implementation on my Mac. However, there is no guarantee that this call
> will select each of the n! permutations with equal probability.
>
> Whether it does will depend on the exact algorithm used by 'sort'. For
> instance, if sort uses the (inefficient for large arrays) bubble sort,
> the last key will end up staying there in half the cases.

Actually, sort_by caches every value passed and uses those for
comparison (aka a Schwartzian Transform), so it would essentially
return the same results as sorting a list of random numbers,
regardless of algorithm.

Sam