公告
财富商城
积分规则
提问
发文
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
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.
(4..10).size #=> 7
(4...10).size #=> 6
YES! :)
(1..5).to_a.inject(:+)
And for visual representation
(1..5).to_a.join("+")+"="+(1..5).inject(:+).to_s
(4..10).to_a * " + " + " = 15" #=> 4 + 5 + 6 + 7 + 8 + 9 + 10 = 15
:)
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.
0
nil
You can use Enumerable methods on Range objects, in this case use Enumerable#inject:
Enumerable
Enumerable#inject
(4..10).inject(:+) #=> 49
Now, in Ruby 2.4.0 you can use Enumerable#sum
(4..10).sum #=> 49
最多设置5个标签!
I assume the ranges whose sums to to be computed are ranges of integers.
By defining
the expression
reduces to
which is simply the formula for the sum of values of an arithmetic progression. Note
(4..10).size #=> 7
and(4...10).size #=> 6
.YES! :)
And for visual representation
:)
Use Enumerable#reduce:
Note that you need
0
as the identity value in case the range to fold is empty, otherwise you'll getnil
as result.You can use
Enumerable
methods on Range objects, in this case useEnumerable#inject
:Now, in Ruby 2.4.0 you can use Enumerable#sum