gpt4 book ai didi

java - 如何计算二维数组中行之间的差异?

转载 作者:太空宇宙 更新时间:2023-11-04 09:19:02 24 4
gpt4 key购买 nike

我是新来的,很高兴加入社区!我在自己想出的练习中遇到了问题,但几天来我一直在努力解决它,所以我认为现在是向您寻求帮助的最佳时机。

我有一个二维数组,想计算列中所有位置之间的差异,然后将它们存储在另一个二维数组中。初始数组有 4 行 3 列。就像 3d 中具有 3 个坐标的 4 个点。

这就是我的想法,非常感谢任何帮助!非常感谢!

import java.util.Arrays;

public class CountingTheDifference {

public static String loop(double[][] twoDArray) {

int length = twoDArray.length;

double[][] differences = new double[length][length];

for (int i = 0; i <= length; i++) {

if (i == 0) {
for (int j = 0; j < twoDArray[i].length; j++) {
differences[i][0] = twoDArray[j][0] - twoDArray[j++][0];

}
} else if (i == 1) {
for (int j = 0; j < twoDArray[i].length; j++) {
differences[i][1] = twoDArray[j][1] - twoDArray[j++][1];
}
}
else {
for ( int j = 0; j < twoDArray[i].length; j++) {
differences[i][2] = twoDArray[j][2] - twoDArray[j][2];
}
}
}

return Arrays.deepToString(differences);
}

public static void main(String[] args) {

double[][] twoArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12,}};
System.out.println(loop(twoArray));
}
}

请帮忙!多萝莎

最佳答案

我已尽可能保持您的代码完整,使用所提供代码中的二维 double 组。

public static String loop(double[][] twoDArray) {

int columns = twoDArray.length;
int rows = twoDArray[0].length;

double[][] differences = new double[columns][rows];

for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
// Absolute difference between the value of this column compared to the previous
// -1 if this is the first column
// Prints: [[-1.0, -1.0, -1.0], [3.0, 3.0, 3.0], [3.0, 3.0, 3.0], [3.0, 3.0, 3.0]]
if (i == 0) {
differences[i][j] = -1;
} else {
differences[i][j] = Math.abs(twoDArray[i][j] - twoDArray[i - 1][j]);
}
}
}

return Arrays.deepToString(differences);
}

public static void main(String[] args) {
double[][] twoArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; // Note that I removed a comma.
System.out.println(loop(twoArray));
}

关于java - 如何计算二维数组中行之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579603/

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