Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.