gpt4 book ai didi

java - 如何编写一个函数来在Java中的二维数组中找到两个最近的点?

转载 作者:行者123 更新时间:2023-12-02 05:33:59 25 4
gpt4 key购买 nike

如何在 Java 中找到数组中两个最近的点?

我的输入是,

int[][] tour = {{0, 0}, {4, 0}, {4, 3}, {0, 3}};

static double calcDistanceBetweenWaypoints(int[] src, int[] dest) {
assert src.length == 2;
assert dest.length == 2;
//(0,0),(0,4)
return Math.sqrt((dest[0] - src[0])*(dest[0] - src[0]) + (dest[1] - src[1])*(dest[1] - src[1]));
}

public static int[][] getClosestWaypoints(int[][] tour) {
throw new UnsupportedOperationException("Not supported yet.");
//I dont know how to do with this function.
}

我的输出是,

closest waypoints    : [(4/0) -> (4/3)], distance: 3,00

最佳答案

另一个解决方案:

public static int[][] getClosestWaypoints(int[][] tour) {
double minDist = Integer.MAX_VALUE;
int[] pt1 = null;
int[] pt2 = null;
for (int i = 0; i < tour.length-1; ++i) {
for (int j = i+1; j < tour.length; ++j) {
double dist = calcDistanceBetweenWaypoints(tour[i], tour[j]);
if (dist < minDist) {
minDist = dist;
pt1 = tour[i];
pt2 = tour[j];
}
}
}
return new int[][] {pt1, pt2};
}

关于java - 如何编写一个函数来在Java中的二维数组中找到两个最近的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56186411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com