Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

comment on

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

This should probably have some error checking to make sure that $start is less than $end, and that $end-$start >= $num. If your intent is that $end shoudl be inclusive it will need small tweak also.

#! perl -slw use strict; sub distinct_random_int{ my($num, $start,$end) = @_; my %uniq; $uniq{ $start + int( rand $end-$start ) } = undef while keys %uniq < $num; return keys %uniq; } print for distinct_random_int 10, 20, 30; __END__ P:\test>388533 27 25 28 21 26 20 22 24 23 29

That works, but if $num is close to being the same size as the range, then you would be better to shuffle the range and then select the first $num elements:

#! perl -slw use strict; use List::Util qw[ shuffle ]; sub distinct_random_int{ my($num, $start,$end) = @_; return ( shuffle $start .. $end )[ 1 .. $num ]; } print for distinct_random_int 10, 20, 30;

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

In reply to Re: How to generate different random numbers? by BrowserUk
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.