R
Richard Gration
Hi all,
I was just looking at List::Util::shuffle (reproduced below) and wondered
where the algorithm came from. Was this invented by the module author? Is
it a known good algorithm for shuffling lists?
It wasn't immediately obvious to me that all elements of the list would be
returned, but I understand what's going on now. Visualising pigeon holes
and bits of paper helps. A bit.
So does anyone know its provenance?
Rich
sub shuffle (@) {
my @a=\(@_);
my $n;
my $i=@_;
map {
$n = int rand($i--);
(${$a[$n]}, $a[$n] = $a[$i])[0];
} @_;
}
I was just looking at List::Util::shuffle (reproduced below) and wondered
where the algorithm came from. Was this invented by the module author? Is
it a known good algorithm for shuffling lists?
It wasn't immediately obvious to me that all elements of the list would be
returned, but I understand what's going on now. Visualising pigeon holes
and bits of paper helps. A bit.
So does anyone know its provenance?
Rich
sub shuffle (@) {
my @a=\(@_);
my $n;
my $i=@_;
map {
$n = int rand($i--);
(${$a[$n]}, $a[$n] = $a[$i])[0];
} @_;
}