有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何计算2d数组中的行之间的差异?

我是新来的,很高兴加入这个社区!我有一个问题,我想出了一个练习,但我试图解决它,因为一些天,所以我认为这是正确的时间向你寻求帮助

我有一个2d数组,希望计算列中所有位置之间的差异,然后将它们存储在另一个2d数组中。初始数组有4行3列。 比如3d中的4个点和3个坐标

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

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) 个答案

  1. # 1 楼答案

    我已经尽可能地保持了代码的灵活性,在提供的代码中使用了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));
    }