什么是最简单,最类似于Ruby的计算数组累积和的方法?
例:
[1,2,3,4].cumulative_sum
Run Code Online (Sandbox Code Playgroud)
应该回来
[1,3,6,10]
Run Code Online (Sandbox Code Playgroud)
khe*_*lll 37
class Array
def cumulative_sum
sum = 0
self.map{|x| sum += x}
end
end
Run Code Online (Sandbox Code Playgroud)
hrn*_*rnt 10
这是一种方式
a = [1, 2, 3, 4]
a.inject([]) { |x, y| x + [(x.last || 0) + y] }
Run Code Online (Sandbox Code Playgroud)
如果答案是多个语句,那么这将更清晰:
outp = a.inject([0]) { |x, y| x + [x.last + y] }
outp.shift # To remove the first 0
Run Code Online (Sandbox Code Playgroud)
irb> a = (1..10).to_a
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb> a.inject([0]) { |(p,*ps),v| [v+p,p,*ps] }.reverse[1..-1]
#=> [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
Run Code Online (Sandbox Code Playgroud)
我们也可以从Haskell那里得到一个注释并制作一个ruby版本的scanr.
irb> class Array
> def scanr(init)
> self.inject([init]) { |ps,v| ps.unshift(yield(ps.first,v)) }.reverse
> end
> end
#=> nil
irb> a.scanr(0) { |p,v| p + v }
=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
irb> a.scanr(0) { |p,v| p + v }[1..-1]
=> [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
irb> a.scanr(1) { |p,v| p * v }
=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
Run Code Online (Sandbox Code Playgroud)