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
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: <%-{-{-{-<
In reply to Re: How do I shuffle an array?
by AnomalousMonk
in thread How do I shuffle an array?
by BramVanOosterhout
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |