以Javascript行方式和列方式查找2d数组的总和

dil*_*had 5 javascript

我想要像这样的数组的总和

1 1 2 = 4

2 2 1 = 5

3 3 1 = 7

= = =

6 6 4

我想在html中使用java脚本打印这样的数组.

Tha*_*you 15

首先将问题分解为更小的部分.我定义了一个基本sum功能,它使用更基本的add功能定义.mapping sum输入数组将为您提供水平和.

垂直总和稍微有些棘手,但并不太难.我定义了一个transpose旋转矩阵的函数.一旦我们旋转,我们可以sum以相同的方式行.

该解决方案适用于任何MxN矩阵

// 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 ]
Run Code Online (Sandbox Code Playgroud)

  • @dilshad,是的,我看到了,但for循环解决方案与洞穴墙上的标记一样粗糙. (4认同)