in reply to Randomize an array

Here's what the Cookbook offers for randomizing arrays:
<br><br># fisher_yates_shuffle( \@array ) : generate a random permutat +ion # of @array in place sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } fisher_yates_shuffle( \@array ); # permutes @array in place
BlueLines

Disclaimer: This post may contain inaccurate information, be habit forming, cause atomic warfare between peaceful countries, speed up male pattern baldness, interfere with your cable reception, exile you from certain third world countries, ruin your marriage, and generally spoil your day. No batteries included, no strings attached, your mileage may vary.

Replies are listed 'Best First'.
RE: RE: Randomize an array
by Anonymous Monk on Sep 09, 2000 at 02:03 UTC
    The 'next if..' line in this post, and the 'unless ...' clause in the next post are unneccessary, and slow the algorithm down for an array of ~20 elements or larger.

    This is because if you assume the cost of a comparison is 1, and the cost of a swap is ~10, then when $i > 10, the savings on a swap are lost because odds are < 1 in 10 that you're swapping the same element. Benchmark comparison against swapping, and do the math. YMMV.