in reply to •Re: Select three random numbers between 1..10
in thread Select three random numbers between 1..10
Out of curiosity, why did you choose to build a new list instead of transposing items within the existing one:
my @sample = (1..10); my $n = 3; for my $l (0..$n-1) { my $r = rand (@sample); @sample[ $l, $r ] = @sample[ $r, $l ]; } print join (", ", @sample[0..$n-1]), "\n";
Transposition is safe against multiple hits to the same index, since each swap just shuffles the list a bit more. That eliminates the need to cull values that have already been seen, as you do with the pop at the tail of your loop.
Even the degenerate case, where $l equals $r, leaves the list no less shuffled than it was before. And since every non-degenerate swap exchanges two values in the list, even the value left in place by a degenerate swap has a good chance of being moved by another, later swap.
|
|---|