简体   繁体   中英

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

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]
]

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

Using ECMAScript6, you can do:

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

The sum of rows is rather easy to illustrate. Let's consider a 3x3 matrix which is easier to format here:

[ 1 2 3 ] -- reduce --> 6  \
[ 7 2 6 ] -- reduce --> 15  } -- map --> [ 6, 15, 7 ]
[ 4 1 2 ] -- reduce --> 7  /

The sum of columns is less trivial. We 'reduce' by 'mapping' 2 rows at a time:

      [ 1 2 3 ]                     [ 8 4 9 ]
    + [ 7 2 6 ]   -- reduce -->   + [ 4 1 2 ]
      ---------                     ---------
map = [ 8 4 9 ]              map = [ 12 5 11 ]

The follwoing code is showing two examples using map

The first sums the 2D array horizontally.

    var array = [ [1,2,3], [3,2,1] ];
    var sum= array.map( function(row){
      return row.reduce(function(a,b){ return a + b; }, 0);
    });

The second sums the 2D array vertically.

var array = [ [1,2,3], [3,2,1] ];
var sum2= array.map(function(row, i) {
  return array.map(function(row) {
    return row[i]; }
  ).reduce(function(a, b) {
    return a+b;
  }, 0);
});

Check working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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