Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
Re: Is there a better way to generate unique set of random numbers ?by moritz (Cardinal) |
on Jul 28, 2011 at 09:44 UTC ( [id://917231]=note: print w/replies, xml ) | Need Help?? |
I'd do it like this:
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. Also note that for testing it is better to reduce the maximum number so that collision become more likely - I tested it with 12 instead of 1185. Update: If the maximal number is the same or not much larger than the number of random values you want, this would probably be faster:
That is, first generating a random permutation, and then selecting some of the elements. But as always it's best to Benchmark the different solutions with real-world data.
In Section
Seekers of Perl Wisdom
|
|