I have 500x500 grid and random coordinates on this grid. I'm trying to get new random coordinates but they shouldn't be too close to the previous ones. I'm come up with this: In an infinite loop I assign a new random value to a variable and if this value satisfies the condition (it's bigger or smaller on a certain quantity (which may change)) then I'm breaking the loop.
int oldX = (int) (Math.random() * 500);
int oldY = (int) (Math.random() * 500);
int newX;
int newY;
int minDistance = 10;
while (true) {
newX = (int) (Math.random() * 500);
if (newX <= (oldX - minDistance) | newX >= (oldX + minDistance)) {
break;
}
}
while (true) {
newY = (int) (Math.random() * 500);
if (newY <= (oldY - minDistance) | newY >= (oldY + minDistance)) {
break;
}
}
But it feels to me not right somehow. Maybe there's a better solution?
Just to remove the repetitious while
loop code blocks into a method call instead and, assuming the 500 x 500
grid starts at index 0 and ends at index 499 which would make the current random formula correct as those values are reachable. If 500 is to be inclusive then the current random formula is incorrect as that value is not reachable. You would have to change 500
to 501
to make 500
inclusive.
This also assumes that newX
and newY
will eventually become oldX
and oldY
respectively.
int x = 0, y = 0;
int minDistance = 10;
x = getRandom(x, minDistance);
y = getRandom(y, minDistance);
System.out.println(String.format("%-3d - %-3d", x, y)); // Optional
The getRandom()
Method:
public static int getRandom(int currentXorY, int minDistance) {
int rnd = currentXorY;
while (rnd >= (currentXorY - minDistance) && rnd <= (currentXorY + minDistance)) {
rnd = (int) (Math.random() * 500);
}
return rnd;
}