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.


In reply to Re^2: Pick k numbers at random by haukex
in thread Pick k numbers at random by Chuma

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.