Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

awt

point

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?

like image 778
trs Avatar asked Jan 24 '26 06:01

trs


1 Answers

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.

like image 130
xpapad Avatar answered Jan 25 '26 20:01

xpapad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!