红宝石:两个数组的总和对应的成员 [英] ruby: sum corresponding members of two arrays
问题描述
我有两个(或更多)阵列,在每个12个整数(值相对应的每个月)。我想要的是将它们添加在一起,这样我得为每月汇总值单个阵列。这里有三个值的示例:
[1,2,3]和[4,5,6] => [5,7,9]
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.
推荐答案
这里的转
版本阿努拉格建议:
Here's the transpose
version Anurag suggested:
a.transpose.map {|x| x.reduce(:+)}
这将与任意数量的分量数组的工作。 减少
和注
是同义词,但减少
在我看来,在这里更清楚地传达code的意图...
This will work with any number of component arrays. reduce
and inject
are synonyms, but reduce
seems to me to more clearly communicate the code's intent here...
这篇关于红宝石:两个数组的总和对应的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!