我有一个像这样的整数数组
[20, 25, 40, 60]
如何将其变成一个数组,每个元素代表之前元素的累积值,包括它自己?
[20, 45, 85, 145]
我正在使用Rails 3.2.0&红宝石1.9.3
答案 0 :(得分:6)
s = 0
[20, 25, 40, 60].map{|e| s += e}
答案 1 :(得分:2)
[20, 25, 40, 60].reduce([]) do |arr, v|
arr << (arr.last || 0) + v
end
或丑陋一个班轮。
[20, 25, 40, 60].reduce([0]){ |a, v| a << a[-1] + v }[1..-1]
答案 2 :(得分:1)
array = [20, 25, 40, 60]
(array.size - 1).times { |i| array[i + 1] += array[i] }
puts array
# => [20, 45, 85, 145]
答案 3 :(得分:0)
B = cumsum(A)
class Array
def ruby_cumsum!
(1..size-1).each {|i| self[i] += self[i-1] }
self
end
end
答案 4 :(得分:0)
arr.each_with_index.map{|x, i| x + (i==0 ? 0 : arr[0..i-1].inject(:+))}
=> [20, 45, 85, 145]
答案 5 :(得分:0)
arr = [20, 25, 40, 60]
first = []
sum = 0
arr.each do |e|
sum += e
first << sum
end
puts first