使用 JavaScript 计算二维矩阵中对角线和的减法

我在hackerrank练习,我有一个二维矩阵的练习。我在实施中遇到错误

  • 11 2 4

  • 4 5 6

  • 10 8 -12

我需要对主对角线求和: 11 + 5 - 12 = 4 在另一个对角线 4 + 5 +10 = 19 最后 19 - 4 = 15

function diagonalDifference(arr) {

     var sumRigth = 0;

     var sumLeft = 0;

     var array = new Array();

     for(var i = 0; i < arr.length ; i++ ){

          for(var j = 0; j < arr[i].length; j++){

               array.push(arr[i][j]);

          }

     }

     for (var i = 0 ; i < array.length; i = i + 4){

          sumRigth += array[i];

     }

     for (var j = 2 ; j < array.length - 1 ; j = j + 2 ){

          sumLeft += array[j];

     }

     return sumLeft - sumRigth;

}


牧羊人nacy
浏览 144回答 3
3回答

30秒到达战场

你可以试试这个function sumDiagonal(matrix) {&nbsp; &nbsp; let firstSum = 0, secondSum = 0;&nbsp; &nbsp; for (let row = 0; row < matrix.length; row++) {&nbsp; &nbsp; &nbsp; &nbsp; firstSum += matrix[row][row];&nbsp; &nbsp; &nbsp; &nbsp; secondSum += matrix[row][matrix.length - row - 1];&nbsp; &nbsp; }&nbsp; &nbsp; console.log(firstSum + ' ' + secondSum);&nbsp; &nbsp; console.log(firstSum-secondSum);}sumDiagonal([[11,2,4],[4,5,6],[10,8,-12]]);

一只斗牛犬

我不认为你在正确的道路上。一个通用的解决方案是首先对从左上角到右下角的元素求和(此处另存为sumRigth)。然后,对从右上角到左下角的元素求和(此处另存为sumLeft)。我理所当然地认为数组包含数字并且大小相同。function diagonalDifference(array) {&nbsp; &nbsp; &nbsp;let sumRigth = 0, sumLeft = 0, count = 0;&nbsp; &nbsp; &nbsp;for (var i = 0 ; i < array.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sumRigth += array[i][count++];&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;count = array.length-1;&nbsp; &nbsp; &nbsp;for (var i = 0; i < array.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sumLeft += array[i][count--];&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return sumLeft - sumRigth;}let arr = [&nbsp; &nbsp; &nbsp;[11, 2, 4],&nbsp; &nbsp; &nbsp;[4, 5, 6],&nbsp; &nbsp; &nbsp;[10, 8, -12]];console.log(diagonalDifference(arr));

慕沐林林

您可以采用一个循环并直接获得两个值进行求和。function getValue(matrix) {&nbsp; &nbsp; let sum = 0;&nbsp; &nbsp; for (let i = 0, l = matrix.length; i < l; i++)&nbsp; &nbsp; &nbsp; &nbsp; sum += matrix[i][l - i - 1] - matrix[i][i];&nbsp; &nbsp; return sum;}console.log(getValue([[11, 2, 4], [4, 5, 6], [10, 8, -12]]));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript