根据条件在数组中添加项目

时间:2017-02-02 01:57:18

标签: ruby

my_array=[6, 2, 7, 1, 10, 0, 9, 0, 8, 2, 10, 0, 10, 0, 3, 5, 7, 2, 5, 5]

如果值为10,那么我应该在10之后的数字之后获取接下来的两个值,并将这些值添加到10。我在做这件事时遇到了麻烦。

对于最后的'10':该值应该总计为15。

2 个答案:

答案 0 :(得分:2)

def sum_groups(arr, val, group_size)
  arr.each_index.select { |i| arr[i]==val }.map do |i|
    arr[i, group_size].reduce(0) { |t,n| t+n.to_i }
  end
end

my_array=[6, 2, 7, 1, 10, 0, 9, 0, 8, 2, 10, 0, 10, -1, 3, 5, 7, 2, 5, 10, 5]

sum_groups(my_array, 10, 3)
  #=> [19, 20, 12, 15] 

sum_groups(my_array, 10, 4)
  #=> [19, 19, 17, 15] 

使用Ruby 2.4+,我们可以使用Array#sum来简化一下:

def sum_groups(arr, val, group_size)
  arr.each_index.select { |i| arr[i]==val }.map do |i|
    arr[i, group_size].sum { |n| n.to_i }
  end
end

或用

替换倒数第三行
arr[i, group_size].map(&:to_i).sum

答案 1 :(得分:-1)

试试这个

[*my_array, 0, 0].each_cons(3).select { |a, b, c| a == 10 }.map(&:sum)

这实际上就是你所描述的

  • each_cons(3)所有三人小组的调查员
  • select选择以10
  • 开头的内容
  • map(&:sum)将它们映射出来

我们用两个零填充数组,当阵列碰巧有一个接近结尾的10时。如果你不在乎这种情况,请将填充物留下。