http://www.perlmonks.org?node_id=31475


in reply to Randomize an array

I recommend the Fisher-Yates Shuffle. See my node on the topic.
# The Fisher-Yates Shuffle sub Shuffle { my $arrayref = shift; my $index = @$arrayref; while ( $index-- ) { my $newloc = int rand (1+$i); # next if $index == $newloc; # Not needed in Perl. @$arrayref[$index, $newloc] = @$arrayref[$newloc, $index]; } }
The line I commented out is part of the Fisher-Yates Shuffle, but its a waste of time in Perl, since the swap is done correctly. (If it were an XOR swap then you would want the next in there)

Replies are listed 'Best First'.
Re^2: Randomize an array
by Anonymous Monk on Jul 01, 2008 at 20:56 UTC
    That code has an error and it doesn't actually randomize. Here's the correct version:
    # The Fisher-Yates Shuffle sub Shuffle { my $arrayref = shift; my $index = @$arrayref; while ( $index-- ) { my $newloc = int rand (1+$index); # next if $index == $newloc; # Not needed in Perl. @$arrayref[$index, $newloc] = @$arrayref[$newloc, $index]; } }