Reputation: 1141
I know how to get a range of random numbers between 0 zero and any number.
But what I want to know is, since the random number generator is not truly random, and follows a specific algorithm, for example if you pass a seed of 20. then it will always generate the same sequence of numbers: 17, 292, 0, 9.
So I get that. Since it follows a specific algorithm, is there a way I can force the generator to always start at zero or any other number?
But specifically zero in my case.
Upvotes: 3
Views: 2421
Reputation: 5394
No need to hack the Random class, just write your own:
public class RandomGenerator {
private int bound;
private Random random;
private boolean firstCall = true;
public RandomGenerator(int bound, long seed) {
this.bound = bound;
random = new Random(seed)
}
public int next() {
if (firstCall) {
firstCall = false;
return 0;
}
return random.nextInt(bound);
}
}
Upvotes: 5
Reputation: 12347
public static void main (String[] args) throws java.lang.Exception
{
int x = -1;
long seed = 0;
int xxx = 100;
while(x!=0){
Random s = new Random(seed++);
x = s.nextInt(xxx);
}
System.out.println("seed " + (seed-1) + " gives " + new Random(seed-1).nextInt(xxx));
}
This will find a seed that the next int will be zero for a given modulus. (Happens to be 18 for this example).
Upvotes: 0