Как рассчитать разницу между строками в 2d массиве? - PullRequest
1 голос
/ 27 октября 2019

Я новичок здесь и рад присоединиться к сообществу! У меня возникла проблема с заданием, которое я придумала, но я пытаюсь решить его несколько дней назад, поэтому я подумала, что сейчас самое время обратиться к вам за помощью.

У меня есть 2dмассив и хотел бы рассчитать различия между всеми позициями в столбцах, а затем сохранить их в другом 2d массиве. Исходный массив имеет 4 строки и 3 столбца. Как 4 точки с 3 координатами в 3d.

Это то, что я придумал, любая помощь очень ценится! Большое спасибо!

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 голосов
/ 27 октября 2019

Я держал ваш код в такте, насколько это возможно, используя двойной массив 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));
}
...