3

I have two arrays:

a = [[1,2],[3,4]];
b = [[5,6],[7,8]];

I want the resultant array to be their sum, i.e.,

c = [[6,8],[10,12]];

Would there be an elegant way to do so?

Note:

I currently know that to simply add a = [1,2] with b = [3,4] to get c = [4,6] I need to do

c = [a,b].transpose.map{|x| x.reduce(:+)};

but I'm not sure how to, if possible, extend this to my problem.

3 Answers 3

4
a.zip(b).map { |x,y| x.zip(y).map { |s| s.inject(:+)  } }
Sign up to request clarification or add additional context in comments.

Comments

3
c = [a, b].transpose.map{|ary| ary.transpose.map{|ary| ary.inject(:+)}}

Comments

3

An alternative, with better expression for manipulating numbers, would be to use 'narray'

require 'narray'
a = NArray[[1,2],[3,4]]
b = NArray[[5,6],[7,8]]

c = a + b

. . . yes really, c = a + b and it is much faster too.

You do pay for this though - NArray expects all the elements to contain the same type of object. If that's the case, and especially if your real-world problem has much larger matrices, then I highly recommend narray for handling this kind of data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.