ruby - 扭曲的部分总和(加到前一个元素)
问题描述
我有一个整数数组,比如说
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{ .... }
或类似的。有人知道如何做得更好吗?
解决方案
这可行,但看起来很奇怪,因为您应该在循环内调用输入数组:
a.each_with_object([]).with_index do |(_, array), index|
array << (index.zero? ? 0 : array[index - 1] + a[index - 1])
end
推荐阅读
- javascript - 为什么此绑定不适用于 javascript 中的类
- python - 在 Mac 上是否有一种方便的方法可以将 .py 文件打包为 Windows 系统的可执行文件?
- java - Kongchen/swagger-maven-plugin 枚举生成
- android - 在 android studio 中找不到导航抽屉布局
- visual-studio - 在将部件/任务从工具栏拖到 Visual Studio 设计图面时,我可以在哪里修改默认 ID/名称?
- laravel - 使用txt文件而不是数据库来获取当前计数器值更好吗?
- php - 如何通过 PHP 正确跟踪每次打开的邮件?
- nginx - 启动 nginx.service 失败:未找到单元
- c# - WPF - 如何在安装程序的目录中生成文件?
- objective-c - 如何在 Objective-C 中使用正则表达式获取 MFA 模式?