英文:
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,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论