I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java’s Random class.
long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);
This implementation (source) gives me a long integer, but what I really want is an integer between 0 and a maximum.
public int random(int max){ /*...*/}
What it is the most efficient way to implement this method?
I had some fun with your code and came up with this:
I did a simple test and it is about Four times as fast as the
java.util.RandomIf you are intrested in how it works you can read this paper:
Disclamer: