How to sum two dimensional arrays

1.6k views Asked by At

I have a two dimensional array = [[12,34,35,21],[10,14,23,17],...] infinity.

I would like to do this in ruby;

arr1 = [array[0][0]+array[1][0]+array[n+1][0]...,
array[0][1]+array[1][1]+array[n+1][1]...,
array[0][2]+array[1][2]+array[n+1][2]...,
array[0][3]+array[1][3]+array[n+1][3]...] 

result (4x4)

arr1 = [[12+10+..],[34+14+..],[35+23..],[21+17+..]]

Any idea?

3

There are 3 answers

3
Santhosh On BEST ANSWER

You can use Array#transpose, and then sum each individual Array

array = [[12,34,35,21],[10,14,23,17]]

array.transpose.map {|a| a.inject(:+) }
# => [22, 48, 58, 38]

If you are using Ruby 2.4 or greater, you can use the Array#sum method

array.transpose.map(&:sum)
# => [22, 48, 58, 38] 

For the output to be an Array or Arrays,

array.transpose.map {|a| [a.sum] }
# => [[22], [48], [58], [38]] 
0
Gourav On

I have just written ruby code

h = Hash.new(0)
arr =  [[12, 34, 35, 21], [10, 14, 23, 17], [1, 2, 3]]  #Any size of nested array
arr.each do |a|
  a.each_with_index do |n,i|
    h[i]+=n
  end
end
h.values.map{|a| [a]}

Hope it helps

0
Grant Hutchins On

You can also use Vector from the standard library matrix gem.

require "matrix"

array_of_arrays = [
  [12, 34, 35, 21],
  [10, 14, 23, 17],
  # ...
]

vectors = array_of_arrays.map { |array| Vector[*array] }
summed_vector = vectors.inject { |memo, vector| memo + vector }

puts summed_vector # => Vector[22, 48, 58, 38]

You can substitute Matrix when your elements are multi-dimensional themselves.