简体   繁体   中英

Finding the diagonal sum of 2D array

const diagonalSum = function (arr) {
    var length=arr.length -1;
     var sum=0;
     for(let i=0;i<arr.length;i++){//1<3
         sum+= arr[i][i]+arr[i][length-i]//[1][0]+
     }
       return sum;
   };

tried this, but 2nd and 3rd test cases are not getting passed. Any other logic?

const diagonalSum = function (arr) {
    var length=arr.length -1;
     var sum=0;
     for(let i=0;i<arr.length;i++){//1<3
         sum+= arr[i][i]+arr[i][length-i]//[1][0]+
     }
       return sum;
   };

searching any other logic

If you are trying to find the diagonal sum of both the diagonals of 2d Array using single for loop, below is the solution

const diagonalSum = function (arr) {
  sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum = sum + arr[i][i] + arr[i][(arr[i].length - 1) - i]
  }
  return sum;
};

Your code looks good to me. Here are a few test cases:

 const diagonalSum = function (arr) { let maxIdx = arr.length - 1; let sum = 0; for(let i=0; i < arr.length; i++) { sum += arr[i][i] + arr[i][maxIdx-i]; } return sum; }; const matrix1 = [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ]; const matrix2 = [ [1, 2, 3], [4, 5, 6], [7, 8, 0] ]; const matrix3 = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1] ]; console.log({ matrix1: diagonalSum(matrix1), matrix2: diagonalSum(matrix2), matrix3: diagonalSum(matrix3) });

Output:

{
  "matrix1": 6,
  "matrix2": 21,
  "matrix3": 8
}

Please provide a some test cases that fail.

This will work for you.

// An efficient Javascript program to find // sum of diagonals

function  printDiagonalSums(mat,n)
    {
        let principal = 0, secondary = 0;
        for (let i = 0; i < n; i++) {
            principal += mat[i][i];
            
        }
     
        document.write("Principal Diagonal:"
                                + principal+"<br>");
                                     
        
    }
     
    // Driver code
     
        let a = [[ 1, 2, 3, 4, 5],
                    [5, 6, 7, 8, 5 ],
                    [ 1, 2, 3, 4, 5 ],
                    [ 5, 6, 7, 8, 5],
                [ 5, 6, 7, 8, 5]];
     
        printDiagonalSums(a, 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM