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

时间:2019-10-27 12:54:48

标签: java arrays multidimensional-array

我是这里的新人,很高兴加入社区!我在想出一个练习时遇到问题,但是几天以来我一直在努力解决这个问题,所以我认为现在是向您寻求帮助的合适时机。

我有一个2d数组,想计算列中所有位置之间的差,然后将它们存储在另一个2d数组中。初始数组有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));
}
}

请帮助! 桃乐丝

1 个答案:

答案 0 :(得分:0)

我已使用提供的代码中的2D双精度数组尽可能保持代码完好。

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));
}