http://qs321.pair.com?node_id=695755


in reply to Random Derangement Of An Array

for my $i (1..$#a) { my $random= rand( $i); swap(\$a[$i], \$a[$random]); }
Since any position is only swapped once with any of the previous places, there can't be the initial value in any place. But still any value can go to any other position in the array. Per induction I think I can show that the values are equally distributed.

EDIT: Thanks Joost, I was too sloppy, even used { instead of [. If I remember correctly it would work without the \ since @_ in the sub is an alias to the parameters, but this way the side effect is more obvious