在2d数组中添加对角线值

JDB*_*JDB 2 java arrays 2d

我有以下2d数组

        int [][] array = {{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9},
                          {10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
                          {20, 21, 22, 23, 24, 25, 26, 27, 28, 29},
                          {30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
                          {40, 41, 42, 43, 44, 45, 46, 47, 48, 49},
                          {50, 51, 52, 53, 54, 55, 56, 57, 58, 59},
                          {60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
                          {70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
                          {80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
                          {90, 91, 92, 93, 94, 95, 96, 97, 98, 99}};
Run Code Online (Sandbox Code Playgroud)

我有这个代码来查找数组中所有值的总和.如何修改它只添加从0开始的对角线值(0 + 11 + 22 + 33等)?

 public static int arraySum(int[][] array)
{
    int total = 0;

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

    return total;
}
Run Code Online (Sandbox Code Playgroud)

GSi*_*ngh 12

由于对角线处于完美的方形,您只需要一个环来添加对角线.


从orgin添加对角线:

public static int arraySum(int[][] array){
    int total = 0;

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

        total += array[row][row];
    }

    return total;
}
Run Code Online (Sandbox Code Playgroud)

添加两个对角线:

从orgin添加对角线:(注意它将中心添加两次......如果需要,你可以减去一个)

public static int arraySum(int[][] array){
    int total = 0;

    for (int row = 0; row < array.length; row++)
    {
        total += array[row][row] + array[row][array.length - row-1];
    }

    return total;
}
Run Code Online (Sandbox Code Playgroud)


dav*_*ave 5

public static int arraySum(int[][] array)
{
    int total = 0;

    for (int index = 0; index < array.length; index++)
    {
            total += array[index][index];
    }

    return total;
}
Run Code Online (Sandbox Code Playgroud)

这当然假设尺寸为mxm.