Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a cumulative sum to an array for only one value?

I have an array of arrays with x and y values:

[[some_date1, 1], [some_date2, 3], [some_date3, 5], [some_date4, 7]]

The result should only sum the y values (1, 3, 5, 7) so that the result is like this:

[[some_date1, 1], [some_date2, 4], [some_date3, 9], [some_date4, 16]]

How is this possible in Ruby?

like image 975
Tomanow Avatar asked Oct 22 '25 18:10

Tomanow


2 Answers

Yes, this is possible in Ruby. You can use [map][1] and do something like this:

sum = 0
array.map {|x,y| [x, (sum+=y)]}

This is how it works. For the given the input:

array = ["one", 1], ["two", 2]

It will iterate through each of the elements in the array e.g.) the first element would be ["one", 1].

It will then take that element (which is an array itself) and assign the variable x to the first element in that array e.g.) "one" and y to the second e.g.) 1.

Finally, it will return an array with the result like this:

=> ["one", 1], ["two", 3]
like image 97
Scott Bartell Avatar answered Oct 24 '25 07:10

Scott Bartell


You can use map:

a = [[:some_date1, 1], [:some_date2, 3], [:some_date3, 5], [:some_date4, 7]]

sum = 0
a.map { |f, v| [f, (sum = sum + v)]}

=> [[:some_date1, 1], [:some_date2, 4], [:some_date3, 9], [:some_date4, 16]]

Since sum will be nil in the first iteration it is necessary to call to_i on it.

like image 44
jbr Avatar answered Oct 24 '25 08:10

jbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!