in reply to How do I shuffle an array?

The shuffle loop will never include the last element of the array. ... rand($i + 1) will never return the value of $i.

BramVanOosterhout: Have you checked these assertions of How do I shuffle an array??

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub fisher_yates_shuffle_while_loop { my $array = shift; my $i = @$array; while ( --$i ) { my $j = int rand( $i+1 ); @$array[$i,$j] = @$array[$j,$i]; } } ;; my @ra = (1 .. 9); fisher_yates_shuffle_while_loop(\@ra); dd \@ra; @ra = (1, 2); fisher_yates_shuffle_while_loop(\@ra); dd \@ra; @ra = (1); fisher_yates_shuffle_while_loop(\@ra); dd \@ra; ;; ;; sub fisher_yates_shuffle_for_loop { my $array = shift; my $i = @$array; for ( my $i = @$array; $i; $i-- ) { my $j = int rand( $i+1 ); @$array[$i,$j] = @$array[$j,$i]; } } ;; @ra = (1 .. 9); fisher_yates_shuffle_for_loop(\@ra); dd \@ra; @ra = (1, 2); fisher_yates_shuffle_for_loop(\@ra); dd \@ra; @ra = (1); fisher_yates_shuffle_for_loop(\@ra); dd \@ra; ;; ;; for (0 .. 9) { printf '%d ', int rand(3 + 1); } " [6, 3, 8, 9, 1, 7, 5, 2, 4] [2, 1] [1] [9, 4, 8, 3, 1, 6, 7, 2, 5, undef] [undef, 2, 1] [undef, 1] 0 3 3 3 3 0 1 1 2 1
The undefs running through the outputs of the for-loop implementation suggest a serious problem. The problem may stem from the notion that  scalar @array yields the index of the highest element in the array; in fact, it yields the number of elements in the array, and  $#array yields the highest index. (This assumes the default value of 0 for the Perl special, now deprecated, variable  $[ (see perlvar). I haven't checked, but maybe you can get correct behavior from the for-loop version if you change  $[ to 1 — but don't do that!)

Update: I've since checked, and it does seem as if the given for-loop implementation works correctly with  $[ == 1 — but again, don't do that!


Give a man a fish:  <%-{-{-{-<