【问题标题】:Given n, generate all permutations of size lesser than 0.5n给定 n,生成所有大小小于 0.5n 的排列
【发布时间】: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


【解决方案1】:

对于您的值“N 的一半”等于 3,这将是:

using Combinatorics
Iterators.flatten(permutations.(powerset(1:3,1)))

注意这是非分配的,所以如果你想看到结果collect是必需的:

julia> collect(Iterators.flatten(permutations.(powerset(1:3,1))))
15-element Array{Array{Int64,1},1}:
 [1]
 [2]
 [3]
 [1, 2]
 [2, 1]
 [1, 3]
 [3, 1]
 [2, 3]
 [3, 2]
 [1, 2, 3]
 [1, 3, 2]
 [2, 1, 3]
 [2, 3, 1]
 [3, 1, 2]
 [3, 2, 1]

【讨论】:

  • 非常感谢!如果不是从来没有的话,需要很长时间才能找到:)
  • 好吧,我意识到我想要的是:collect(Iterators.flatten(permutations.(powerset(1:7,0, floor(Int, 7/2)))))(这实际上是第一段中提出的问题,但在实例和代码中描述得很糟糕)但是你让我用你的答案找到了它,所以我我不会编辑我的问题,也不会取消你的答案,再次感谢:)
  • 这个命令也会生成一个空集[]。如果您想避免它,请将1 作为起始值而不是零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多