【发布时间】:2017-11-01 11:04:21
【问题描述】:
我有一个二维数组,我在其中存储一些点以获得最近的两个点,例如: "(-1, 3), (-1, -1), (1, 1), (2, 0.5) , (2, -1) , (3, 3) ,(4, 2) , (4, 0.5)" 结果是:"(1.0, 1.0) and (2.0, 0.5)" 而且效果很好:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of points");
int numberOfPoints = scanner.nextInt();
//setting number of rows, number of column is unable to change
double[][] points = new double[numberOfPoints][2];
for (int i = 0; i < points.length; i++) {
points[i][0] = scanner.nextDouble();
points[i][1] = scanner.nextDouble();
}
int point1 = 0, point2 = 1;
double shortestDistance = distance(points[point1][0], points[point1][1],
points[point2][0], points[point2][1]);
//get shortest distance
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0], points[i][1],
points[j][0], points[j][1]);
if (shortestDistance > distance) {
point1 = i;
point2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points is" +
"(" + points[point1][0] + ", " + points[point1][1] + ") and (" +
points[point2][0] + ", " + points[point2][1] + ")");
}
public static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
我试图获得所有最近的点,而不仅仅是两个点。
我试过通过这种方式获取,但它并没有涵盖所有情况,也没有显示所有点:
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (distance(points[i][0], points[i][1],
points[j][0], points[j][1]) == shortestDistance)
System.out.println("The closest two points are " +
"(" + points[i][0] + ", " + points[i][1] + ") and (" +
points[j][0] + ", " + points[j][1] + ")");
}
}
我也尝试初始化新数组并将距离存储到其中然后对其进行排序,但它失败了。
如何显示所有最近的点?
注意:
我没有发现 this question 对我有用。
【问题讨论】:
-
“但它并没有涵盖所有情况” 它在什么方面没有涵盖所有情况?请举个例子。
-
@Andreas 上面的输入只是输出两个点而不是四个。
-
什么4分?没有其他点相距 1.118033988749895。
-
为了证明这一点,here 是打印所有点对之间的所有距离列表的代码,按距离排序。不比较反向对,因为
(1.0, 1.0)和(2.0, 0.5)之间的距离当然与(2.0, 0.5)和(1.0, 1.0)之间的距离相同。如您所见,只有一对点相距1.118033988749895。 -
所以您的意思是,当您找到彼此最接近的 2 个点 (
(1.0, 1.0) - (2.0, 0.5)) 时,您想消除那些然后找到下一个 now 的“对” 彼此最接近((3.0, 3.0) - (4.0, 2.0)),然后重复((2.0, -1.0) - (4.0, 0.5)),最后得到最后一对((-1.0, 3.0) - (-1.0, -1.0))?如果是这样,那么您应该更新问题并实际说,因为我无法从现在的问题中得到答案。
标签: java arrays algorithm math