in reply to Re: Pick k numbers at random
in thread Pick k numbers at random
Shuffling an array and then picking the first k elements would do what I want, but that's still linear in n. The "sample" module seems to be efficient, though.
If you're worried about efficiency, you should measure first.
#!/usr/bin/env perl use warnings; use strict; use Math::Prime::Util qw/randperm/; use List::Util qw/shuffle/; use Algorithm::Numerical::Sample qw/sample/; use Benchmark qw/cmpthese/; die "Usage: $0 N K\n" unless @ARGV==2; my ($N,$K) = @ARGV; cmpthese(-2, { mpu => sub { my @range = randperm($N, $K); }, shuf => sub { my @range = (shuffle 0 .. $N-1)[0 .. $K - 1]; }, samp => sub { my @range = sample (-set => [0 .. $N-1], -sample_size => $K); }, }); __END__ $ perl bench.pl 10 5 Rate samp shuf mpu samp 326934/s -- -86% -91% shuf 2388541/s 631% -- -31% mpu 3456068/s 957% 45% -- $ perl bench.pl 100 5 Rate samp shuf mpu samp 76377/s -- -86% -98% shuf 539280/s 606% -- -86% mpu 3744910/s 4803% 594% -- $ perl bench.pl 10000 5 Rate samp shuf mpu samp 835/s -- -86% -100% shuf 5885/s 605% -- -100% mpu 3719610/s 445489% 63101% -- $ perl bench.pl 100000 5000 Rate samp shuf mpu samp 72.2/s -- -87% -99% shuf 562/s 678% -- -91% mpu 6544/s 8958% 1064% --
Not surprising, since Math::Prime::Util's randperm is implemented in C, and has a bunch of different methods for picking K of N depending on set sizes. See the source.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Pick k numbers at random -- hash keys
by Discipulus (Canon) on Nov 12, 2019 at 20:48 UTC | |
by AnomalousMonk (Archbishop) on Nov 12, 2019 at 23:16 UTC | |
by syphilis (Archbishop) on Nov 13, 2019 at 01:06 UTC | |
by Discipulus (Canon) on Nov 13, 2019 at 08:52 UTC | |
by choroba (Cardinal) on Nov 13, 2019 at 15:55 UTC | |
|
Re^3: Pick k numbers at random
by ikegami (Patriarch) on Nov 14, 2019 at 18:19 UTC |