Find the sum of each row as well as that of each column in 2 dimensional matrix ( m X n)

D V*_*esh 0 javascript arrays

How to find the sum of each row as well as that of each column in 2 dimensional matrix ( m X n).

[
  [1, 2, 3],
  [3, 2, 1]
]
Run Code Online (Sandbox Code Playgroud)

I know in one dimensional array, we can do:

var sum = [5, 6, 3].reduce(add, 0);

function add(a, b) {
  return a + b;
}

console.log(sum);
Run Code Online (Sandbox Code Playgroud)

Arn*_*uld 6

使用 ECMAScript6,您可以执行以下操作:

var matrix = [
  [ 1, 2, 3 ],
  [ 7, 2, 6 ]
];

// sums of rows
var rowSum = matrix.map(r => r.reduce((a, b) => a + b));

// sums of columns
var colSum = matrix.reduce((a, b) => a.map((x, i) => x + b[i]));

console.log(rowSum);
console.log(colSum);
Run Code Online (Sandbox Code Playgroud)

行的总和很容易说明。让我们考虑一个 3x3 矩阵,这里更容易格式化:

[ 1 2 3 ] -- reduce --> 6  \
[ 7 2 6 ] -- reduce --> 15  } -- map --> [ 6, 15, 7 ]
[ 4 1 2 ] -- reduce --> 7  /
Run Code Online (Sandbox Code Playgroud)

列的总和不太重要。我们通过一次“映射”2 行来“减少”:

      [ 1 2 3 ]                     [ 8 4 9 ]
    + [ 7 2 6 ]   -- reduce -->   + [ 4 1 2 ]
      ---------                     ---------
map = [ 8 4 9 ]              map = [ 12 5 11 ]
Run Code Online (Sandbox Code Playgroud)