Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to generate distinct random numbers?

by ysth (Canon)
on Sep 06, 2004 at 05:23 UTC ( [id://388724] : note . print w/replies, xml ) Need Help??


in reply to How to generate distinct random numbers?

This may or may not be appropriate; you haven't really given enough information about how this would be used. (Are you looking for integers or floating point? Is the range going to be in the hundreds or billions? etc.)
sub distinct_random_int { my ($num, $start, $end) = @_; my @rand; my @avail = $start..$end; push @rand, splice(@avail, rand(@avail), 1) for 1..$num; @rand; }

Replies are listed 'Best First'.
Re^2: How to generate distinct random numbers?
by Aristotle (Chancellor) on Sep 06, 2004 at 23:31 UTC

    That is not a fair algorithm. @avail shrinks during your loop, so the range rand(@avail) picks from does as well, and thus chances for any one number to be picked increase with each iteration.

    Makeshifts last the longest.

      No.