简体   繁体   English

求二维数组的对角线和

[英]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如果您尝试使用单个 for 循环查找 2d Array 的两条对角线的对角线和,下面是解决方案

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: 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 // 一个高效的 Javascript 程序,用于查找 // 对角线之和

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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