ruby: sum corresponding members of two or more arr

2019-01-21 22:24发布

I've got two (or more) arrays with 12 integers in each (corresponding to values for each month). All I want is to add them together so that I've got a single array with summed values for each month. Here's an example with three values: [1,2,3] and [4,5,6] => [5,7,9]

The best I could come up with was:

[[1,2,3],[4,5,6]].transpose.map{|arr| arr.inject{|sum, element| sum+element}} #=> [5,7,9]

Is there a better way of doing this? It just seems such a basic thing to want to do.

标签: ruby arrays sum
9条回答
欢心
2楼-- · 2019-01-21 23:01

For:

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

You could zip and then use reduce:

p a.zip(b).map{|v| v.reduce(:+) }
#=> [5, 7, 9]

Or, if you're sure that array a and b will always be of equal length:

p a.map.with_index { |v, i| v + b[i] }
#=> [5, 7, 9]
查看更多
Juvenile、少年°
3楼-- · 2019-01-21 23:02

I humbly feel that the other answers I see are so complex that they would be confusing to code reviewers. You would need to add an explanatory comment, which just increases the amount of text needed.

How bout this instead:

a_arr = [1,2,3]
b_arr = [4,5,6]
(0..2).map{ |i| a_arr[i] + b_arr[i] }

Slightly different solution: (so that you're not hard coding the "2")

a_arr = [1,2,3]
b_arr = [4,5,6]
c_arr = []
a_arr.each_index { |i| c_arr[i] = a_arr[i] + b_arr[i] }

Finally, mathematically speaking, this is the same question as this:

How do I perform vector addition in Ruby?

查看更多
姐就是有狂的资本
4楼-- · 2019-01-21 23:03

Now we can use sum in 2.4

nums = [[1, 2, 3], [4, 5, 6]]
nums.transpose.map(&:sum) #=> [5, 7, 9]
查看更多
登录 后发表回答