How to sum two-dimensional arrays

192 views Asked by At

let's say that I have two-dimensional arrays

array= [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98],  [32,19,66,88],...]

I would like to do this in ruby

arr = [[10+45+32+..,12+48+19,15+41+66+..,17+23+88+..],   [16+36+..,32+25+..,65+74+..,47+98+..]

Thank you in advance.

1

There are 1 answers

4
Sagar Pandya On BEST ANSWER

Use partition to separate and collect the even-indexed sub-arrays and odd-indexed sub-arrays. Then transpose each partition, followed by the sum of each newly formed sub-array.

array = [[10,12,15,17],[16,32,65,47],[45,48,41,23],[36,25,74,98],[32,19,66,88]]

array.partition.with_index { |_,i| i.even? }
               .map { |e| e.transpose.map(&:sum) }
#=> [[87, 79, 122, 128], [52, 57, 139, 145]]

key methods: Enumerable#partition,Integer#even? and Array#transpose. See ruby-docs for more info. If you're using Ruby versions < 2.4.0, use inject(:+) instead of sum, as follows:

array.partition.with_index { |_,i| i.even? }
               .map { |e| e.transpose.map { |e| e.inject(:+) } }
#=> [[87, 79, 122, 128], [52, 57, 139, 145]]