I want to generate random numbers within the range 1 to 4, 4 including.
Here is my code:
int num = r.nextInt(4) + 1; //r is instance of Random.
However, I am running the above code in a loop and don't want repeating random number.
What happens now is often I am getting:1,1,1,2,3,1,4,2,2,1,4,2,4,4,2,1,4,3,3,1,4,2,4,1
as my output.
Here, though the numbers are random within the range(1-4), but often repeated like the number "1"in the first 3 iterations.
What I am looking for is a way to get non repeating random number within the loop.
One simple way I know is of keeping the last random number before current iteration and compare, but I am sure there must be better solution to this.
Thanks in advance.
Use random.nextInt(range-1)
and then map that number to the output number with a function that excludes the previous number:
public class Test {
private final Random random = new Random();
private final int range;
private int previous;
Test(int range) { this.range = range; }
int nextRnd() {
if (previous == 0) return previous = random.nextInt(range) + 1;
final int rnd = random.nextInt(range-1) + 1;
return previous = (rnd < previous? rnd : rnd + 1);
}
public static void main(String[] args) {
final Test t = new Test(4);
for (int i = 0; i < 100; i++) System.out.println(t.nextRnd());
}
}
There is no "better" answer. You are getting a random number. Check this line:
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
this could be perfectly random. So I propose you describe a better requirement. Do you want always a next number that is different from the previous? Do you want a maximum of duplicates in a special rang? lets say within 6 consecutive numbers, every number is allowed to occur twice?
If you bring such a requirement we might be able to help you. otherwise we can just say: what you seeing is really random :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With