【发布时间】:2020-04-24 08:13:06
【问题描述】:
我正在尝试解决以下用例:
输入: 将形成不规则多边形的 x,y 坐标列表(保证它们有效并且线不会相交;但是它可以是凹形的)。输入格式无关紧要,所以我目前分别为 x 和 y 使用两个松散的 int 数组。
输出:此多边形内的random x,y 坐标,它不直接位于角或边缘的顶部。
使用以下代码,我已经能够处理多边形内的随机x,y-坐标:
// Currying Function with two int-arrays as parameters and double-pair return-type
X->Y->{
// Create a Path2D object
java.awt.geom.Path2D path = new java.awt.geom.Path2D.Double();
// Start at the first coordinate given
path.moveTo(X[0], Y[0]);
// Loop over the remaining coordinates:
for(int i=1; i<X.length; i++)
// And draw lines from corner to corner
path.lineTo(X[i], Y[i]);
// After the loop, close the path to finish the polygon
path.closePath();
// Create a Rectangle that encapsulates the entire Path2D-polygon
java.awt.Rectangle rect = s.getBounds();
// The resulting x,y-coordinate, starting uninitialized
double x,y;
// Do-while the Path2D polygon does not contain the random x,y-coordinate:
do{
// Select a random x,y-coordinate within the Rectangle
x = rect.getX() + Math.random()*rect.getWidht();
y = rect.getY() + Math.random()*rect.getHeight();
}while(!path.contains(x,y));
// After which we return this random x,y-coordinate as result:
return new double[]{x,y};
}
这一切都按预期工作。现在我想确保随机 x,y 坐标不是输入 x,y 坐标之一(这很容易)并且不在 Path2D 的边缘/线上。第二部分我不知道如何解决,快速谷歌搜索没有提供任何有用的信息,因此提出了这个问题。
注意:我知道随机点恰好在边缘/角落顶部的可能性很小,可能会被忽略,但这是一个挑战,因此需要实施不管怎样。
【问题讨论】:
-
使用
Line2D及其contains()方法查看随机点是否“在”一条线段上。 -
@Andreas 哦,这听起来确实很有用。有没有办法让所有
Line2D形成Path2D?或者我应该只循环输入数组对来创建Line2Ds? -
您可以使用
PathIterator来查看路径的所有lineTo段,但是从X和@987654335 创建Line2D对象会容易得多@数组。 -
@Andreas 是的,我知道
PathIterator。谢谢想!我在这对输入坐标上创建了一个循环来创建Line2D。如果您愿意,可以将其发布为答案,那么我会接受。 -
不。如果您认为答案对其他人有用,您可以自行回答。否则,只需删除问题。
标签: random java random polygon point point-in-polygon