For long lists, that isn't more efficient than shuffling.
Regardless of the length of the list, which is quicker depends upon the ratio of picks.
...for a small number of picks, Ie. If the ratio of picks to list size is less than ~15%, spliceing is quicker than shuffling the whole list:
#! perl -slw
use strict;
use List::Util qw[ shuffle ];
use Benchmark qw[ cmpthese ];
our $N //= 20;
our $S //= 8;
our @nums = 0 .. $N;
cmpthese -1, {
shuffle => q[ my @s = ( shuffle @nums )[ 0 .. $S-1 ]; ],
splice => q[ my @s = map splice( @nums, rand( @nums ), 1 ), 1 .. $
+S; ],
};
__END__
c:\test>868601 -N=10 -S=2
Rate shuffle splice
shuffle 894654/s -- -10%
splice 993686/s 11% --
c:\test>868601 -N=10 -S=3
Rate splice shuffle
splice 769417/s -- -9%
shuffle 844675/s 10% --
c:\test>868601 -N=100 -S=15
Rate shuffle splice
shuffle 196571/s -- -5%
splice 207873/s 6% --
c:\test>868601 -N=100 -S=17
Rate splice shuffle
splice 186995/s -- -3%
shuffle 192359/s 3% --
c:\test>868601 -N=1000 -S=169
Rate shuffle splice
shuffle 19552/s -- -2%
splice 19968/s 2% --
c:\test>868601 -N=1000 -S=170
Rate splice shuffle
splice 20274/s -- -1%
shuffle 20569/s 1% --
c:\test>868601 -N=10000 -S=1998
Rate shuffle splice
shuffle 1578/s -- -6%
splice 1674/s 6% --
c:\test>868601 -N=10000 -S=1999
Rate splice shuffle
splice 1601/s -- -1%
shuffle 1625/s 2% --
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|