gpt4 book ai didi

java - 比较每组二维数组以确定最大距离

转载 作者:行者123 更新时间:2023-12-02 10:21:54 28 4
gpt4 key购买 nike

所以我在二维数组中有一组元素,我试图确定坐标之间的最大距离。

我已经创建了一个循环来遍历每个元素,但我不知道如何仅比较第一组和第二组,依此类推。几天来我一直在尝试不同的方法,这就是我到目前为止所得到的。

使用公式: 最远距离 = Math.sqrt((Math.pow((maxX - minX), 2))+ (Math.pow((maxY-minY), 2)));

int max = cities[0][0]; //int to store the max of the i column
int min = cities[0][0]; //int to store the max of the i column


int maxX = cities[0][0]; //int to store the max of the i column
int maxY = cities[0][0]; //int to store the max of the i column

int minX = cities[0][0]; //int to store the max of the j column
int minY = cities[0][0]; //int to store the max of the j column




for(int y=1; y<cities[0].length; y++) { //loop through columns
for(int x=0; x<cities[y].length; x++) { //loop through lines


if(cities[x][y] > max) { //if the number at the column i and line j is bigger than max

max = cities[x][y];
maxX = cities[x][0];
maxY = cities[0][y];
}
if(((cities[x][0]) < min) && (cities[0][y] < min)) { //if the number at the column i and line j is bigger than max
min = cities[x][y];

minX = cities[x][0];
minY = cities[0][y];

}


}
}
System.out.println("the maxX is " +maxX+ " the minX is " + maxY);
System.out.println("the maxX is " +minX+ " the minX is " + minY);



}


}

对于我的示例数组:
int[][] 城市 = {{-48,-4},{23,-45},{-7,-40},{-28,31},{36,24},{23,-11} ,{36,-10},{-9,21}};

预期输出应约为 91.5259。任何帮助/指导将不胜感激!!

最佳答案

如果理解得很好,您只需执行一个双 for 循环即可评估每对城市 (i,j) 之间的距离,并在较大距离时更新最大距离。这可以轻松完成:

public static void main (String[] args) {
int[][] cities = {{-48,-4},{23,-45},{-7,-40},{-28,31},{36,24},{23,-11},{36,-10},{-9,21}};

double maxDistance = 0;
for (int i = 0; i < cities.length-1; i++) {
for (int j = i+1; j < cities.length; j++) {
maxDistance = Math.max(getDistance(cities[i], cities[j]), maxDistance);
}
}
System.out.println("The max distance is " + maxDistance);
}

private static double getDistance(int[] city1, int[] city2) {
int dx = city1[0] - city2[0];
int dy = city1[1] - city2[1];
return Math.sqrt(dx*dx + dy*dy);
}

请注意,ji+1cities.length,因为您只需要检查 unordered pairs (i,j) 因为距离(i,j) == 距离(j,i)。

<小时/>

Java 8 替代方案:

double maxDistance  = Arrays.stream(cities)
.flatMapToDouble(city1 -> Arrays.stream(cities).mapToDouble(city2 -> getDistance(city1, city2)))
.max()
.orElseThrow(IllegalArgumentException::new); //Or any other exception

关于java - 比较每组二维数组以确定最大距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280696/

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