2

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?

Draken
  • 3,134
  • 13
  • 34
  • 54

2 Answers2

6

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]] 
Santhosh
  • 28,097
  • 9
  • 82
  • 87
  • thank you Santhosh for the response, but my array is infinity, this works only if you have 2x4 – user7373737 Jan 04 '17 at 12:09
  • 2
    This doesnt just work for 2x4, it works for a finite Array of arrays of same size. – Santhosh Jan 04 '17 at 12:11
  • 5
    Your array is NOT inifinite. You just can't store an infinite array in memory. The simple reason is that computer memory is limited and you can't store an infinite non-infinitesimal quantity in a finite space. http://av1611.com/kjbp/kjv-dictionary/infinite.html – Ed de Almeida Jan 04 '17 at 12:16
1

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

Gourav
  • 570
  • 3
  • 16