Ruby,合并惰性序列



设惰性序列: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, ....]

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

对于我的例子:

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

是否有宝石等来处理这样的序列

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

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]]

相关内容

  • 没有找到相关文章

最新更新