Just for the record, since everyone's talking about it but noone has shown any code:

use List::Util qw( shuffle ); sub distinct_random_int { my ( $num, $start, $end ) = @_; return if $start > $end or $num > $end - $start + 1; ( shuffle $start .. $end )[ 0 .. $num - 1 ]; }

Update: indeed, so long as the size of the range and the number of elements requested is within an order of magnitude, this is faster than the hash&retry solutions, in my tests by about 20%. If the discrepancy grows any larger, the hash&retry approach becomes much cheaper very quickly.

use strict; use warnings; use Benchmark qw( cmpthese ); use List::Util qw( shuffle ); sub randseq_shuffle { my ( $num, $start, $end ) = @_; return if $start > $end or $num > $end - $start + 1; ( shuffle $start .. $end )[ 0 .. $num - 1 ]; } sub randseq_retry { my ( $num, $start, $end ) = @_; return if $start > $end or $num > $end - $start + 1; my %seen; my $range = $end - $start; my $base = $start; undef $seen{ $base + int rand $range } until $num == keys %seen; keys %seen; } for ( [ 5, 10, 30 ], [ 50, 100, 300 ], [ 500, 1000, 3000 ], [ 5000, 10000, 30000 ], [ 50000, 100000, 300000 ], [ 5000, 10000, 30000 ], [ 500, 10000, 30000 ], [ 50, 10000, 30000 ], [ 5, 10000, 30000 ], ) { my ( $n, $s, $e ) = @$_; cmpthese -1 => { "shuffle($n,$s,$e)" => sub { randseq_shuffle $n, $s, $e }, "retry($n,$s,$e)" => sub { randseq_retry $n, $s, $e }, }; }

Makeshifts last the longest.


In reply to Re: How to generate distinct random numbers? by Aristotle
in thread How to generate distinct random numbers? by johnnywang

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.