簡體   English   中英

二維數組的總和

[英]Sum in 2-dimensional array

我有一個矩陣:

matrix = [[0, 1, 1, 2],
          [0, 5, 0, 0],
          [2, 0, 3, 3]]

我需要計算不小於0的所有數組元素的總和,因此,在此示例中,總和應為= 9

我有這個功能:

function matrixElementsSum(matrix) {
  // Write your code here
 var Summa =0
  for (i = 0; i<4; i++){
      var sum =0;
    // console.log(matrix[i].length); //4
    for(j=0; j<matrix.length; j++){
      console.log("Matrix JI "+ matrix[j][i])
         sum = sum +matrix[j][i]; 
         if (matrix[j][i-1]!=0){
           console.log(matrix[j][i-1])
           Summa =Summa+ sum;
         }
    }
    console.log('-----------' +Summa)
    console.log("Sum "+sum);
  }

  return Summa;
}

我想我需要更改if (matrix[j-1][i]!=0)但是它不起作用

您可以為此使用reduce()forEach()循環內部。 如果foreach循環中的當前元素為零,則可以將該元素的索引存儲在另一個對象zero然后可以使用該對象檢查索引是否為零。

 var matrix = [ [0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3] ] var zero = {} var sum = matrix.reduce(function(r, e, i) { e.forEach(function(n, j) { if (n == 0) zero[j] = true; if (!zero[j]) r += n; }) return r; }, 0) console.log(sum) 

您可以對2個數組求和,而忽略底部數組中的數字,頂部數組中相同索引的項為0。

現在,您可以從末尾迭代矩陣,並對結果數組求和。

 const matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]; const sumNotUnderZero = (bottom, top) => top.map((v, i) => v ? v + bottom[i] : v); const result = matrix.reduceRight(sumNotUnderZero) .reduce((s, n) => s + n); console.log(result); 

您可以使用Array#reduceRight構建具有值列總和的另一個數組,然后對單個數字使用Array#reduce

 var matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]], result = matrix.reduceRight(function (a, b) { return b.map(function (c, i) { return c && c + a[i]; }); }).reduce(function (a, b) { return a + b; }); console.log(result); 

應該能夠簡化並使用它:

function matrixElementsSum(matrix) {
    var Summa =0
    for (i = 0; i < matrix.length; i++)
      for(j = 0; j < matrix[i].length; j++)
         if (matrix[i-1][j] != 0)
           Summa = Summa + matrix[i][j];

    return Summa;
}

需要訪問上述當前的一個第一陣列,因此matrix[i-1]然后在同一列中,因此, [j](matrix[i-1])[j] ~ matrix[i-1][j]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM