[solved] Random numbers not so random? (new java.util.Random).nextInt

Hello,
Using this line, it seems i can generate a number between 0 and 5.

randomNum = (new java.util.Random).nextInt(6)

but I keep getting 5, 5, 5, 5, 0, 0, 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5…

Or something like that. I know any random set of number you’ll see some repeats. But I tried this yesterday for 10 minutes. Never got a 1, 2 or 3.

Am I doing this wrong?

This has to do with how Random number generators work. They use an equation that generates a pseudorandom sequence using a formula. But that formula needs a seed value to get started. If you give it the same seed it will produce the same sequence of numbers every time.

By creating a new Random object every time you need a number you are relying on what ever mechanism Random uses to generate a seed when you don’t provide one for it (probably based on the time of day or something like that). I’m all but positive that is not very random (otherwise why have the Random class in the first place.

I suggest using Random as it was intended and reuse it rather than generating a new one every time.

In the globals section of your rules put

val java.util.Random rand = new java.util.Random

In your rule use:

randomNum = rand.nextInt(6)

If your rule is likely to be triggered such that multiple instances of it are running at the same time or you use the random number generator in multiple rules you may want to use java.util.ThreadLocalRandom instead.

3 Likes

Thanks!