Is there a good way to calculate sum of range elem

2019-07-14 02:59发布

问题:

What is the good way co calculate sum of range?

Input

4..10

Output

4 + 5 + 6 + 7 + 8 + 9 + 10 = 49

回答1:

You can use Enumerable methods on 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 


回答2:

I assume the ranges whose sums to to be computed are ranges of integers.

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

By defining

last = rng.first + rng.size - 1

the expression

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

reduces to

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

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



回答3:

Use Enumerable#reduce:

range.reduce(0, :+)

Note that you need 0 as the identity value in case the range to fold is empty, otherwise you'll get nil as result.



回答4:

(4..10).to_a * " + " + " = 15" 
#=> 4 + 5 + 6 + 7 + 8 + 9 + 10 = 15

:)



回答5:

YES! :)

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

And for visual representation

(1..5).to_a.join("+")+"="+(1..5).inject(:+).to_s


标签: ruby range