Newbie dot Org
Code Snippets
CGI
Shuffle arrays with fisher yates shuffle
|
Here is a handy way to shuffle up an array of data. You pass in a reference to your array and it is shuffled in-place. #!/usr/bin/perl -w
@array = qw(this is a test); shuffle(\@array); print(join(' ', @array), "\n"); exit(); # fisher yates shuffle sub shuffle { my($array) = shift(); for (my $i = @$array; --$i; ) { my($j) = int(rand($i + 1)); next() if ($i == $j); @$array[$i, $j] = @$array[$j, $i]; } } #EOSub exit();
Posted by Staunch on 03/04/01 at 16:04:20
|