3

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

是否有任何宝石等来处理此类序列

4

1 回答 1

6

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

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]]
于 2014-05-14T11:20:49.763 回答