Choosing random numbers efficiently
Posted
by Frederik Wordenskjold
on Stack Overflow
See other posts from Stack Overflow
or by Frederik Wordenskjold
Published on 2010-03-26T13:22:03Z
Indexed on
2010/03/26
13:33 UTC
Read the original article
Hit count: 528
I have a method, which uses random samples to approximate a calculation. This method is called millions of times, so its very important that the process of choosing the random numbers is efficient.
I'm not sure how fast javas Random().nextInt
really are, but my program does not seem to benefit as much as I would like it too.
When choosing the random numbers, I do the following (in semi pseudo-code):
// Repeat this 300000 times
Set set = new Set();
while(set.length != 5)
set.add(randomNumber(MIN,MAX));
Now, this obviously has a bad worst-case running time, as the random-function in theory can add duplicated numbers for an eternity, thus staying in the while-loop forever. However, the numbers are chosen from {0..45}, so a duplicated value is for the most part unlikely.
When I use the above method, its only 40% faster than my other method, which does not approximate, but yields the correct result. This is ran ~ 1 million times, so I was expecting this new method to be at least 50% faster.
Do you have any suggestions for a faster method? Or maybe you know of a more efficient way of generation a set of random numbers.
© Stack Overflow or respective owner