Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the efficiency and quality of this shuffling algorithm?

This recent question about sorting randomly using C# got me thinking about the way I've sometimes shuffled my arrays in Perl.

@shuffled = sort { rand() <=> rand() } @array;

The proposed solution in the mentioned question is Fisher-Yates shuffle, which works in a linear time.

The question is: how efficient is my snippet and is such shuffle "really" random?

like image 237
Tuminoid Avatar asked Dec 17 '08 18:12

Tuminoid


2 Answers

I'm not a Perl internals expert, so I don't know how "sort" will work here. However, most sort functions expect consistency in their comparisons, and I would expect them to work unpredictably if the function is itself random. Unfortunately, unpredictability is not the same as randomness, and so I'd have no confidence in your shuffled array. It may tend to put elements in some sort of order, just as a hastily created and complicated recurrence relation may not be random.

Rather than analyze the sort function, I'd suggest going with Fisher-Yates.

As Knuth said, randomness is too important to be left to chance.

like image 78
David Thornley Avatar answered Oct 04 '22 14:10

David Thornley


$ perldoc List::Util
⋮
  shuffle LIST
       Returns the elements of LIST in a random order

           @cards = shuffle 0..51      # 0..51 in a random order
⋮

That would be my suggestion.

like image 28
derobert Avatar answered Oct 04 '22 13:10

derobert