Adjusting XORShift generator to return a number within a maximum
java, performance, random
Solution
I had some fun with your code and came up with this:
public class XORShiftRandom {
private long last;
private long inc;
public XORShiftRandom() {
this(System.currentTimeMillis());
}
public XORShiftRandom(long seed) {
this.last = seed | 1;
inc = seed;
}
public int nextInt(int max) {
last ^= (last << 21);
last ^= (last >>> 35);
last ^= (last << 4);
inc += 123456789123456789L;
int out = (int) ((last+inc) % max);
return (out < 0) ? -out : out;
}
}
I did a simple test and it is about Four times as fast as the `java.util.Random`
If you are intrested in how it works you can read this paper:
Disclamer:
The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.
Problem
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?