Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Sum of 2d Array in Javascript row wise and column wise [closed]

Tags:

javascript

i want to sum of Array like this

1 1 2 =4

2 2 1 =5

3 3 1 =7

= = =

6 6 4

i want to print like this sum of Array Using java script in html.

like image 717
dilshad Avatar asked Jun 13 '13 04:06

dilshad


People also ask

How do you sum a 2D array?

Let's see how to find the sum of the 2D array using the map function. Initialize the 2D array using lists. Pass the function sum and 2D array to the map function. Find the sum of resultant map object and print it.


1 Answers

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. mapping sum over the input array will give you the horizontal sums.

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.

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 ]
like image 89
Mulan Avatar answered Nov 12 '22 15:11

Mulan