【发布时间】:2021-04-14 02:02:45
【问题描述】:
给定一个整数 n,我想尽可能高效地将所有大小小于或等于 0.5n 的整数的排列生成为一个向量。
例如,n=7 将是:
15-element Array{Array{Int64,1},1}:
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
我目前的想法是生成所有大小为k 小于0.5n 的排列并附加它们:
using Combinatorics
function generate_half_perm(n)
half_n = floor(Int, n/2)
result = []
for l in 1:half_n
for c in permutations(1:half_n, l)
push!(result, c)
end
end
return result
end
generate_half_perm(7) 然后给出这篇文章的第一个实例。我认为这段代码目前高于O(2^(n/2).n),这是代码的复杂性,没有生成组合所需的代码combinations(1:half_n, l)。
我想知道是否有任何更好的想法可以导致更快的代码,因为我的 n 可能会超过 100。
我有使用 this code [Optimal way to compute permutations in Julia] 的想法,但生产功能已被弃用,应根据此 other answer [How to replace consume and produce with channels] 替换,现在这开始变得复杂,我无法理解!
如果您在算法上有更好的想法,但没有 Julia 实现,我很乐意尝试:)
小编辑:我意识到我想要的是:
collect(Iterators.flatten(permutations.(powerset(1:7,0, floor(Int, 7/2)))))
感谢@Przemyslaw Szufel 让我找到它 :)
【问题讨论】:
-
对于 n=100,有太多太多,无法存储在地球上的所有内存中。如果 n=100,则有 ~ 3e64 大小 n/2 个。
-
@dmuir,是的,你是对的!我将尽我所能运行我的项目,然后永远不会达到 100 :)
标签: arrays algorithm optimization julia permutation