ruby: sum corresponding members of two or more arrays

前端 未结 9 753
孤独总比滥情好
孤独总比滥情好 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:50

    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 about 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?

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

    Now we can use sum in 2.4

    nums = [[1, 2, 3], [4, 5, 6]]
    nums.transpose.map(&:sum) #=> [5, 7, 9]
    
    0 讨论(0)
  • 2020-12-13 09:53

    For clearer syntax (not the fastest), you can make use of Vector:

    require 'matrix'
    Vector[1,2,3] + Vector[4,5,6]
    => Vector[5, 7, 9]
    

    For multiple vectors, you can do:

    arr = [ Vector[1,2,3], Vector[4,5,6], Vector[7,8,9] ]
    arr.inject(&:+)
    => Vector[12, 15, 18]
    

    If you wish to load your arrays into Vectors and sum:

    arrays = [ [1,2,3], [4,5,6], [7,8,9] ]
    arrays.map { |a| Vector[*a] }.inject(:+)
    => Vector[12, 15, 18]
    
    0 讨论(0)
提交回复
热议问题