创建一个函数来构建一组特定的组合

Making a function to build a particular set of combinations

我正在尝试创建一个函数 f 这样

f(1) == ((1,),)
f(2) == ((1,), (2,), (1,2))
f(3) == ((1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3))
f(4) == ((1,), (2,), (3,), (4,), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4))

等等。任何人对如何以编程方式生成它有任何聪明的想法?我确定此操作有一些奇特的名称,但我不确定它是什么。

julialang slack 上给我的两个答案:

using Combinatorics

f(n) = unique(sort.(vcat([collect(permutations(1:n, i)) for i in 1:n]...)))
jointuple(x,y) = (x...,y...)
function f(x) 
    if x == 0
        []
    elseif x == 1
        [(1,);]
    else 
        a = f(x-1) 
        vcat(a,(x,),map(z->jointuple(z,x),a)) 
    end 
end

组合包有这个:

using Combinatorics

combinations(1:n) # iterator of all combinations

例如

julia> collect(combinations(1:3))
7-element Array{Array{Int64,1},1}:
 [1]      
 [2]      
 [3]      
 [1, 2]   
 [1, 3]   
 [2, 3]   
 [1, 2, 3]

注意combinations是一个迭代器,可以在for循环中使用

for c in combinations(1:n)
    ...
end

无需一次在内存中创建所有组合(只有 collect 迭代器才能创建它们)。 combinations returns 一个 Vector 而不是一个元组,这样 c 的类型不会在迭代之间改变。

https://discourse.julialang.org/t/generate-all-subsets-of-a-set/12810/10 中有一些附加信息。