【问题标题】:ruby - Sum consecutive duplicate numbers in an arrayruby - 对数组中的连续重复数字求和
【发布时间】:2021-05-31 03:58:24
【问题描述】:

假设我有一个仅包含整数(正数和负数)的列表/数组。我想制作一种方法,只获取相同且连续的数字的总和。结果应该是一个数组,如下面的示例所示。 “相同”条件含义:1 == 1

例子:

[1,4,4,4,0,4,3,3,1] # => [1,12,0,4,6,1]
So as you can see sum of consecutives 1 is 1 
sum of 3 consecutives 4 is 12 
sum of 0... and sum of 2 
consecutives 3 is 6 ...

[1,1,7,7,3] # => [2,14,3]
[-5,-5,7,7,12,0] # => [-10,14,12,0]

我试过这个,但是没有连续条件,我要怎么添加那个条件?

def sum_consecutives(string)
  string.map{|num| string.count(num) > 1 ? num * string.count(num) : num}
end

提前致谢:-)

【问题讨论】:

    标签: arrays ruby methods sum conditional-statements


    【解决方案1】:

    您可以将原始数组拆分为连续数字的块:Enumerable#chunk_while

    a = [1,4,4,4,0,4,3,3,1]
    a.chunk_while {|a,b| a == b }
    #=> [[1], [4, 4, 4], [0], [4], [3, 3], [1]]
    

    然后只需对子数组进行映射和求和:Enumerable#sum

    a.chunk_while {|a,b| a == b }.map(&:sum) 
    #=> [1, 12, 0, 4, 6, 1]
    

    【讨论】:

    • 谢谢,我不知道块枚举器,工作得很好。顺便说一句,我最终得到了这个:string.chunk_while {|a,b| a == b; }.to_a.map{|set| set.count*set[0]}
    • @SamP to_a 不是必需的,只需创建一个中间件 Array 即可处理,您可以在之后立即使用 map,例如a.chunk_while {|a,b| a == b }.map{|set| set.size*set.first}
    猜你喜欢
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2022-12-03
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2019-01-22
    相关资源
    最近更新 更多