Home > other >  Finding the diagonal sum of 2D array
Finding the diagonal sum of 2D array

Time:12-27

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

CodePudding user response:

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;
};

CodePudding user response:

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.

CodePudding user response:

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);
  • Related