julia – 使用迭代器合并多个已排序流。

huangapple go评论52阅读模式
英文:

julia - merging multiple streams in sorted order using iterators

问题

如何使用迭代器按排序顺序合并这些数组?这些数组已排序,但值可能会重复出现。
由于数组可能比内存大,所以要使用迭代器。
该函数应允许合并任意数量的迭代器。

a = [1, 1, 4, 5, 8, 9]
b = [2, 6, 7]

mergesort(a, b, ...)
英文:

How do i merge these arrays using iterators in sorted order? The arrays are sorted but values may appear more than once.
Using iterators since the arrays may be bigger than memory.
The function should allow for any number of iterators to be combined.

a = [1, 1, 4, 5, 8, 9]
b = [2, 6, 7]

mergesort(a, b, ...)

答案1

得分: 2

以下是使用Iterators.Stateful的示例:

a = [1, 1, 4, 5, 8, 9]
b = [2, 6, 7]
c = [2, 3, 4, 6]

iters = [Iterators.Stateful(arr) for arr in [a, b, c]]

while !isempty(iters)
    firsts = peek.(iters)
    _, idx = findmin(firsts)
    print(popfirst!(iters[idx]), ", ")
    isempty(iters[idx]) && deleteat!(iters, idx)
end

这段代码会输出:1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9,

英文:

Here is one with Iterators.Stateful:

a = [1, 1, 4, 5, 8, 9]
b = [2, 6, 7]
c = [2, 3, 4, 6]

iters = [Iterators.Stateful(arr) for arr in [a, b, c]]


while !isempty(iters)
    firsts = peek.(iters)
    _, idx = findmin(firsts)
    print(popfirst!(iters[idx]), ", ")
    isempty(iters[idx]) && deleteat!(iters, idx)
end

which prints 1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9,

huangapple
  • 本文由 发表于 2023年6月29日 08:10:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定