in reply to Re: Is there a better way to generate unique set of random numbers ?
in thread Is there a better way to generate unique set of random numbers ?
If you need to generate many more than 10 distinct random numbers, this solution will be faster because the hash lookup works in constant time, whereas your solution has to iterate over the whole array for each number. For 10 there won't be a big difference.But do note that the only reason your algorithm guarantees to terminate is because rand uses a pseudo random number generator. Were rand to be truly random, neither algorithm could guarantee to be finished before Perl 6 dominates the world.
Here's an algorithm that does terminate:
use List::Util 'shuffle'; my @set = (shuffle(0..1184))[0..9];
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Is there a better way to generate unique set of random numbers ?
by moritz (Cardinal) on Jul 28, 2011 at 10:09 UTC | |
by happy.barney (Friar) on Jul 28, 2011 at 10:52 UTC | |
by JavaFan (Canon) on Jul 28, 2011 at 10:48 UTC |