Florian F. wrote:
Daniel W. wrote:
Florian F. wrote:
Don’t do this, better use (1…10).sort_by { rand }. Your version is
equivalent to (1…10).sort { 1 } and always creates the same
permutation for this array.
It’s random for me. Both work.
No, really, it isn’t. It may “look random”, but try sorting (1…10) many
times and ponder the coincidence.
That’s because sort{ foo } expects foo to be in -1,0,1.
rand() is always [0, 1).
rand(2)-1 is (-1,1) however and thus will work just fine.
One could do sort{rand <=> rand}, but that’s ~9x slower by my testing.
irb(main):163:0> (1…10).to_a.sort{rand }
=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
irb(main):164:0> (1…10).to_a.sort{rand }
=> [10, 6, 1, 7, 3, 8, 5, 9, 4, 2]
irb(main):165:0> (1…11).to_a.sort{rand }
=> [11, 6, 1, 7, 3, 8, 5, 9, 4, 10, 2]
irb(main):166:0> (1…12).to_a.sort{rand }
=> [12, 7, 1, 8, 3, 9, 5, 10, 2, 11, 6, 4]
vs
irb(main):186:0> (1…12).to_a.sort{rand(2) -1}
=> [1, 2, 6, 11, 9, 4, 8, 7, 5, 10, 3, 12]
irb(main):187:0> (1…12).to_a.sort{rand(2) -1}
=> [1, 9, 8, 3, 5, 6, 11, 4, 2, 10, 7, 12]