admin管理员组文章数量:1331631
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);
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);
Share
Improve this question
edited May 12, 2019 at 19:13
adiga
35.3k9 gold badges65 silver badges87 bronze badges
asked Aug 2, 2016 at 12:49
D V YogeshD V Yogesh
3,7001 gold badge31 silver badges40 bronze badges
2
- 1 Possible duplication of question: stackoverflow./questions/15083103/… – GH Karim Commented Aug 2, 2016 at 12:52
- 1 duplication is not Possible ,in your above link answer is available total sum of two dimensional array, but i want row and as well as col separably,simple menting and giving down vote is not good – D V Yogesh Commented Aug 2, 2016 at 13:17
2 Answers
Reset to default 9Using 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
本文标签:
版权声明:本文标题:javascript - Find the sum of each row as well as that of each column in 2 dimensional matrix ( m X n) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742223442a2435598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论