Is there a good way to calculate the sum of the elements of a range in ruby

What is a good way to calculate the sum of the amount?

Enter

4..10

Output

4 + 5 + 6 + 7 + 8 + 9 + 10 = 49
+2
source share
5 answers

You can use methods Enumerablefor Range objects, in this case use Enumerable#inject:

(4..10).inject(:+)
 #=> 49 

Now in Ruby 2.4.0 you can use Enumerable # sum

(4..10).sum
#=> 49 
+7
source

I assume that the ranges whose sums are to be calculated are integer ranges.

def range_sum(rng)
  rng.size * (2 * rng.first + rng.size - 1) / 2
end

range_sum(4..10)   #=> 49
range_sum(4...10)  #=> 39
range_sum(-10..10) #=>  0

Defining

last = rng.first + rng.size - 1

expression

rng.size * (2 * rng.first + rng.size - 1) / 2

comes down to

rng.size * (rng.first + last) / 2

which is just a formula for the sum of the values ​​of an arithmetic progression. Note (4..10).size #=> 7and (4...10).size #=> 6.

+6
source

Enumerable # reduce:

range.reduce(0, :+)

Please note that you need 0as the identifier value in case the reset range is empty, otherwise you will get nilas the result.

+3
source

YES!:)

(1..5).to_a.inject(:+)

And for visual presentation

(1..5).to_a.join("+")+"="+(1..5).inject(:+).to_s
+2
source
(4..10).to_a * " + " + " = 15" 
#=> 4 + 5 + 6 + 7 + 8 + 9 + 10 = 15

:)

+2
source

Source: https://habr.com/ru/post/1662359/


All Articles