首页 > 解决方案 > 扭曲的部分总和(加到前一个元素)

问题描述

我有一个整数数组,比如说

a=[4, 6, 7, 2]

我想生成一个大小相同的新数组,具有以下属性:

- The first array, b[0], is 0
- For the remaining elements, b[n] is the sum of all elements from a[0] up to a[n].

因此,对于a上面,b应该变成[0, 4, 10, 17]

效率不是问题(虽然我想重用已经计算的部分总和,而是一次又一次地重新计算它们),但结果应该是可以理解的。

我想出了以下解决方案:

b=[nil]*a.size
ind=-1
b.map! {|i| (ind >= 0 ? (a[ind]+b[ind]) : 0).tap {ind+=1}};

这行得通,但我不太喜欢它,主要是因为“backindex”变量ind和需要 preallocate b。我想要类似的东西

b = a.map{ .... }

或类似的。有人知道如何做得更好吗?

标签: ruby

解决方案


这可行,但看起来很奇怪,因为您应该在循环内调用输入数组:

a.each_with_object([]).with_index do |(_, array), index|
  array << (index.zero? ? 0 : array[index - 1] + a[index - 1])
end

推荐阅读