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?
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.
$ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With