trs
trs

Reputation: 2454

java: generate a random point that is not inside a rectangle

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

Answers (3)

xpapad
xpapad

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

Ficik
Ficik

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

kidhuvig
kidhuvig

Reputation: 134

Generate a random point. Then check if it is inside bounds of rectangle. if it is then:

  1. Let centerX and centerY be the x and y of the center point of rectangle.
  2. if randPointX < centerX then let randPointX = randPointX - centerX
  3. if randPointX > centerX then let randPointX = randPointX + centerX
  4. Do same for y ordinate
  5. you will need to do bounds checking again to see if the point is outside the larger view (screen i'm assuming). Just warp coordinates. so if randPointX is negative then let it equal max_X + randPointX

Upvotes: 0

Related Questions