Is there a good way to calculate sum of range elem

2019-07-14 03:05发布

What is the good way co calculate sum of range?

Input

4..10

Output

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

标签: ruby range
5条回答
We Are One
2楼-- · 2019-07-14 03:11

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楼-- · 2019-07-14 03:20

YES! :)

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

And for visual representation

(1..5).to_a.join("+")+"="+(1..5).inject(:+).to_s
查看更多
放我归山
4楼-- · 2019-07-14 03:22
(4..10).to_a * " + " + " = 15" 
#=> 4 + 5 + 6 + 7 + 8 + 9 + 10 = 15

:)

查看更多
Rolldiameter
5楼-- · 2019-07-14 03:23

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.

查看更多
Anthone
6楼-- · 2019-07-14 03:28

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 
查看更多
登录 后发表回答