本文介绍了在二维矩阵(m X n)中找到每一行以及每一列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在二维矩阵(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);


推荐答案

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

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

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

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 ]

这篇关于在二维矩阵(m X n)中找到每一行以及每一列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 10:44