ruby: sum corresponding members of two or more arrays

前端 未结 9 751
孤独总比滥情好
孤独总比滥情好 2020-12-13 09:01

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 su

相关标签:
9条回答
  • 2020-12-13 09:35

    @FriendFX, you are correct about @user2061694 answer. It only worked in Rails environment for me. You can make it run in plain Ruby if you make the following changes...

    In the IRB

    [[0, 0, 0], [2, 2, 1], [1,3,4]].transpose.map {|a| a.inject(:+)}
     => [3, 5, 5]
    
    
    [[1,2,3],[4,5,6]].transpose.map {|a| a.inject(:+)}
     => [5, 7, 9]
    
    0 讨论(0)
  • 2020-12-13 09:38

    here's my attempt at code-golfing this thing:

    // ruby 1.9 syntax, too bad they didn't add a sum() function afaik
    [1,2,3].zip([4,5,6]).map {|a| a.inject(:+)} # [5,7,9]
    

    zip returns [1,4], [2,5], [3,6], and map sums each sub-array.

    0 讨论(0)
  • 2020-12-13 09:39

    This might not be the best answer but it works.

    array_one = [1,2,3]
    array_two = [4,5,6]
    x = 0
    array_three = []
    while x < array_one.length
      array_three[x] = array_one[x] + array_two[x]
      x += 1
    end
    
    =>[5,7,9]
    

    This might be more lines of code than other answers, but it is an answer nonetheless

    0 讨论(0)
  • 2020-12-13 09:43
    [[1,2,3],[4,5,6]].transpose.map{|a| a.sum} #=> [5,7,9]
    
    0 讨论(0)
  • 2020-12-13 09:43

    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]
    
    0 讨论(0)
  • 2020-12-13 09:49

    Here's the transpose version Anurag suggested:

    [[1,2,3], [4,5,6]].transpose.map {|x| x.reduce(:+)}
    

    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...

    0 讨论(0)
提交回复
热议问题