gpt4 book ai didi

Java-获取数字周围的所有值

转载 作者:行者123 更新时间:2023-12-02 11:52:49 25 4
gpt4 key购买 nike

我想制作一个矩阵,它可以更改该位置上的数字值加上其上方、下方、左侧和右侧的值/求和。

  • 如果没有元素则加0。

目前的问题是9 3 9 | 6 12 6 | 6 12 6 9 3 9 但它们应该是 9 10 9 | 6 10 6| 9 10 9(只是从左到右,从左到右),我不知道上面的值是谁得到的。

有人可以帮我吗?

此外,我想在自动循环中执行此操作,但我总是得到这个ArrayIndexOutOfBoundsException

  • 输入矩阵为1 8 1 | 4 2 4 | 4 2 4 1 8 1 结果应该是 13 12 13 | 8 26 8 | 8 26 8 13 12 13

    public class Matrix {
    public static void main(String[] args) {

    int[][] matrix = { { 1, 8, 1 }, { 4, 2, 4 }, { 1, 8, 1 } };
    print(matrix);

    System.out.println("\n");
    int[][] blur = blurMatrix(matrix);
    print(blur);
    }

    public static int[][] blurMatrix(int[][] matrix) {
    if (matrix == null)
    return null;
    if (matrix.length <= 0)
    return null;

    int[][] blur = new int[matrix.length][];

    for (int row = 0; row < blur.length; row++) {
    blur[row] = new int[matrix[row].length];

    for (int col = 0; col < blur[row].length - 1; col++) {
    int cellValue = matrix[row][col];
    int nextColValue = matrix[row][col + 1];
    // int lastColValue = matrix[row][col-1];
    // int nextRowValue = matrix[row+1][col];
    // int lastRowValue = matrix[row-1][col];

    blur[row][col] = cellValue + nextColValue;// +lastColValue+nextRowValue+lastRowValue;
    }

    int lastColumnIndex = blur[row].length - 1;
    blur[row][2] = blur[row][0];
    blur[row][1] = matrix[row][2] + matrix[row][0] + matrix[row][2];

    }

    return blur;

    }

    public static void print(int[][] m) {

    if (m == null) {
    System.out.print(" no matrix to print!");
    return;
    }

    for (int row = 0; row < m.length; row++) {

    for (int col = 0; col < m[row].length; col++) {

    System.out.print(m[row][col] + " ");

    }
    System.out.println("");
    }

    }
    }

最佳答案

您需要一个条件,一个第三 if-then-else 表达式。

int cols = matrix[row].length;

int nextColValue = col+1 < cols ? matrix[row][col+1] : 0;
int lastColValue = col-1 >= 0 ? matrix[row][col-1] : 0;

... + nextColValue + lastColValue + ...

当然你可以这样做:

int valueAt(int[][] m, int row, int col) {
if (0 > row || row >= m.length) {
return 0;
}
int[] v = m[row];
if (0 > col || col >= v.length) {
return 0;
}
return v[col];
}

... = valueAt(matrix, row, col)
+ valueAt(matrix, row-1, col)
+ valueAt(matrix, row+1, col)
+ valueAt(matrix, row, col-1)
+ valueAt(matrix, row, col+1);

矩阵[0][-1]导致ArrayIndexOutOfBoundsException的问题就这样避免了。

关于Java-获取数字周围的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775666/

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