在Java中按行和按列查找2d数组的总和 [英] Find Sum of 2d Array in Javascript row wise and column wise
问题描述
我想像这样对Array求和
i want to sum of Array like this
1 1 2 = 4
1 1 2 =4
2 2 1 = 5
2 2 1 =5
3 3 1 = 7
3 3 1 =7
= = =
6 6 4
我想使用html中的java脚本打印像这样的Array总和.
i want to print like this sum of Array Using java script in html.
推荐答案
首先将问题分解为小块.我定义了一个基本的 sum
函数,该函数使用一个更基本的 add
函数定义.在输入数组上 map
ping sum
将为您提供水平总和.
Start by breaking the problem down into smaller pieces first. I defined a basic sum
function which is defined using an even more basic add
function. map
ping sum
over the input array will give you the horizontal sums.
垂直总和有些棘手,但不太难.我定义了一个 transpose
函数,该函数旋转矩阵.轮换后,我们可以用相同的方式 sum
行.
The vertical sums are little more tricky, but not too tough. I defined a transpose
function which rotate our matrix. Once we rotate, we can sum
the rows the same way.
此解决方案适用于任何 MxN 矩阵
This solution works on any MxN matrix
// generic, reusable functions
const add = (x,y) => x + y
const sum = xs => xs.reduce(add, 0)
const head = ([x,...xs]) => x
const tail = ([x,...xs]) => xs
const transpose = ([xs, ...xxs]) => {
const aux = ([x,...xs]) =>
x === undefined
? transpose (xxs)
: [ [x, ...xxs.map(head)], ...transpose ([xs, ...xxs.map(tail)])]
return xs === undefined ? [] : aux(xs)
}
// sample data
let numbers = [
[1,1,1],
[2,2,2],
[3,3,3],
[4,4,4]
]
// rows
console.log(numbers.map(sum))
// [ 3, 6, 9, 12 ]
// columns
console.log(transpose(numbers).map(sum))
// [ 10, 10, 10 ]
这篇关于在Java中按行和按列查找2d数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!