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

泪湿孤枕 提交于 2020-01-04 11:02:15

问题


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


来源:https://stackoverflow.com/questions/40707971/is-there-a-good-way-to-calculate-sum-of-range-elements-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!