java:生成不在矩形内的随机点
我有许多矩形,并且正在尝试生成一个不在其中任何一个内部的随机点。我创建了一个方法来执行此操作,但这似乎导致我的应用程序冻结,因为在生成有效点之前它必须经过大量点:
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;
}
是否有什么我做错了,或者是否有更多有效的方法来做到这一点,这样它就不会冻结我的应用程序?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
生成随机点。然后检查它是否在矩形的边界内。如果是则:
Generate a random point. Then check if it is inside bounds of rectangle. if it is then:
我会尝试这样的事情:
选择该点是否位于矩形的上方/下方/左侧/右侧(nextInt(4)),然后在该区号中选择随机点
:
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:
如果第一次尝试没有成功,此代码将导致无限循环,okPoint = true 必须位于 do< /strong> 阻止。当你解决这个问题时,看看你的表现如何。
当您检查多个矩形而不仅仅是一个矩形时,我想不出一种更快的方法。
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.