Esa Mäkinen Esa Mäkinen -4 years ago 109
Ruby Question

Cumulative inverse array sum in Ruby

I am calculating the sum of array values from each index to end of array. Like so:

array = [50, 40, 30,20]{|x,i| x = array[i..array.length].reduce(:+) }
=> [140, 90, 50, 20]

Is there any cleaner, ruby-like and more efficent way of doing this? Cumulative array sums are already discussed here.

Answer Source

As you mentioned efficient, I am not following your code of map.with_index way: it have time complexity of O(n^2)

Inverse cumulative_sum can be done with cumulative_sum and 2 reverse:

# cumulative sum with O(n) complexity
# from
class Array
    def cumulative_sum
        sum = 0{|x| sum += x}

array = [50, 40, 30, 20]
p array.reverse.cumulative_sum.reverse
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download