in reply to Select three random numbers between 1..10
First, just don't call srand, it isn't useful here. At least you didn't pass an argument to it. :)
I find it unfortunate that List::Util's shuffle() doesn't support stopping the shuffle process after the first N new items have been selected. This makes using it for this situation somewhat inefficient. But to really make it inefficient, you should pick from a really huge list. But, having a really huge list means this method becomes inefficient in memory as well as in wasting a lot of time doing shuffling that doesn't matter.
So here is a solution that scales very well as far as memory and CPU use is concerned. It isn't as flexible (it only lets you select from a range of integers) and it probably isn't even faster for such small cases as originally requested, but it was an interesting challenge. Maybe I should add it to Algorithm::Loops.
It uses the same algorithm as the Fisher-Yates shuffle, but using a sparse array.
use strict; use warnings; # My solution: sub pickInts { my( $count, $min, $max )= @_; my( @pick, %pick ); while( 0 < $count-- ) { my $i= int( $min + rand($max-$min+1) ); for( $pick{$i} ) { $i= $_ if defined; $_= $min++; } push @pick, $i; } return wantarray ? @pick : \@pick; } # For comparison: #use List::Util qw( shuffle ); # I don't have this module, so I stole its code: sub shuffle (@) { my @a=\(@_); my $n; my $i=@_; map { $n = rand($i--); (${$a[$n]}, $a[$n] = $a[$i])[0]; } @_; } # Sample uses: # Pick 3 integers from the range 1..10: my @list= pickInts( 3, 1, 10 ); print "@list\n"; print join " ", (shuffle(1..10))[0..2], $/; $|= 1; # Pick 10 integers from the range 100000..999999: @list= pickInts( 10, 100000, 999999 ); print "@list\n"; print join " ", (shuffle(100000..999999))[0..9], $/;
which produces the output like:
> perl pick.pl 2 1 9 4 10 9 676232 765332 337745 257079 672444 306794 410807 382463 952100 532838 ^C >
Sorry, I didn't have time to wait for the full output. (:
- tye
(Trivial updates applied)
|
|---|