seebs
4/30/2007 3:08:00 AM
In message <deb2337a0704291945w6d65facai51ce887daae4a9dc@mail.gmail.com>, "Rick DeNatale" write
s:
>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.
DOH!
> 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.
Yes.
However, the sort is doing a lot more comparisons and swaps. It's
O(n*log(n)), while the straight shuffle is O(n). On an array of
10,000 items, shuffling uses 20,000 assignments. Sorting by rand
used 132,000 comparisons, and that would imply a fair number of
swaps. Total time difference is about a factor of three.
I'm willing to trade a little conciseness for that.
-s