Traverse an array diagonally

后端 未结 2 1745
我寻月下人不归
我寻月下人不归 2020-12-30 06:53

I have a large array of arbitrary size. It\'s a square array. I\'m trying to grasp how to traverse it diagonally like a / rather than a \\ (what I

2条回答
  •  臣服心动
    2020-12-30 07:08

    Much simpler way is to check the sum if indexes are equals to the array.length = 1; for diagonalRight and for diagonalLeft just check if i is equals j

    Example:

    digonalLeft sums \ of matrix, because (0,0) (1,1) (2,2) makes the diagonal. diagonalRight sums / of matrix, because (0+2) = (1+1) = (2+0) = 2 and 2 is the array.length - 1.

    long diagonalLeft = 0;
    long diagonalRight = 0;
    
    for (int i = 0; i < array.lenth - 1; i++) {
        for (int j = 0; j < array.length -1; j++) {
            if (i == j) digonalLeft += array[i][j];
            if (i + j == array.length - 1) diagonalRight += array[i][j];
        }    
    }
    

提交回复
热议问题