gpt4 book ai didi

Ruby,合并惰性序列

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:55 24 4
gpt4 key购买 nike

让我有惰性序列:s1, s2, s3, ..., sN,带有非降序数字,例如:

s1 = [1, 1, 2, 3, 3, 3, 4, .....]
s2 = [1, 2, 2, 2, 2, 2, 3, 3, 4, ....]
s3 = [1, 2, 3, 3, 3, 3, 4, 4, 4, ....]

我想做的是合并它,按相似的项目分组并用一些函数处理它,例如生成元组列表(数字,计数)

对于我的情况:

merge(s1, s2, s3) 应该生成 [ [1, 4], [2, 6], [3, 9], [4, 5], .. ..]

是否有任何gem等来处理这样的序列

最佳答案

如果你想懒惰地做,这里有一些代码可以做到这一点:

def merge(*args)
args.map!(&:lazy)
Enumerator.new do |yielder|
while num = args.map(&:peek).min
count = 0
while list = args.find { |l| l.peek == num }
list.next
list.peek rescue args.delete list

count += 1
end
yielder.yield [num, count]
end
end
end

s1 = [1, 1, 2, 3, 3, 3, 4]
s2 = [1, 2, 2, 2, 2, 2, 3, 3, 4]
s3 = [1, 2, 3, 3, 3, 3, 4, 4, 4]
s4 = (0..1.0/0)

merge(s1, s2, s3, s4).take(20)
# => [[0, 1], [1, 5], [2, 8], [3, 10], [4, 6], [5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1], [11, 1], [12, 1], [13, 1], [14, 1], [15, 1], [16, 1], [17, 1], [18, 1], [19, 1]]

关于Ruby,合并惰性序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23653112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com