I have 500×500 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?
1