Reputation: 2454
I have a number of rectangles, and am trying to generate a random point that is not inside any of them. I created a method to do this, but it appears that this is causing my application to freeze because it has to go through a large number of points before a valid point is generated:
public Point getLegalPoint() {
Random generator = new Random();
Point point;
boolean okPoint = true;
do {
point = new Point(generator.nextInt(975), generator.nextInt(650));
for (int i = 0; i < buildingViews.size(); i++) {
if (buildingViews.get(i).getBuilding().getRectangle()
.contains(point)) {
okPoint = false;
break;
}
}
} while (okPoint == false);
return point;
}
Is there something I am doing wrong, or is there a more efficient way to do it so that it won't freeze my application?
Upvotes: 2
Views: 1949
Reputation: 4456
This code results to infinite loop if you don't succeed on the first try, okPoint = true must be inside the do block. See what your performance is when you fix that. I cannot think of a faster way as you check against multiple rectangles and not just one.
Upvotes: 9
Reputation: 148
I would try something like this: select whether the point is above/below/on left side/on right side of rectange (nextInt(4)) and then select random point in this area
code:
public Point getLegalPoint(int x, int y, int width, int height){
Random generator = new Random();
int position = generator.nextInt(4); //0: top; 1: right; 2: bottom; 3:right
if (position == 0){
return new Point(generator.nextInt(975),y-generator.nextInt(y);
} else if (position == 2){
return new Point(generator.nextInt(975),y+height+(generator.nextInt(650-(y+height)));
}
... same for x ...
}
Upvotes: 0
Reputation: 134
Generate a random point. Then check if it is inside bounds of rectangle. if it is then:
Upvotes: 0