你能帮我吗? 我该怎么做才能找到集合中所有子集的代码
例如
我想用Julia编写此约束。这是一个子行程约束。但是我不知道如何找到S集的所有子集。
@constraint(ILRP,
c7[k in totalK, t in totalH],
sum(x[i,j,k,t] for i=1:totalS, j=1:totalS)<=size(S)-1);
非常感谢
答案 0 :(得分:4)
您可以使用Combinatorics.jl软件包中的powerset
函数来获取它,例如:
julia> using Combinatorics
julia> x = [1:5;]
5-element Array{Int64,1}:
1
2
3
4
5
julia> powerset(x)
Base.Iterators.Flatten{Array{Combinatorics.Combinations{Array{Int64,1}},1}}(Combinatorics.Combinations{Array{Int64,1}}[Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 0), Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 1), Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 2), Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 3), Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 4), Combinations{Array{Int64,1}}([1, 2, 3, 4, 5], 5)])
julia> collect(powerset(x))
32-element Array{Array{Int64,1},1}:
[]
[1]
[2]
[3]
[4]
[5]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3, 5]
[1, 2, 4, 5]
[1, 3, 4, 5]
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
请注意,默认情况下,powerset
返回一个迭代器,以避免分配所有子集。
另外,您可以向powerset
传递第二个和第三个位置参数,以限制返回子集的最小和最大大小,例如:
julia> collect(powerset(x, 2, 3))
20-element Array{Array{Int64,1},1}:
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
答案 1 :(得分:1)
不知道这是您要寻找的东西
使用组合语
function subsets(A::AbstractArray,r::Union{AbstractArray,Integer}) o= Array{Array{eltype(A),1},1}(undef,0) if typeof(r)<:Integer r>length(A) && (r=[length(A)]) r=[r...] elseif typeof(r)<:UnitRange r[end]>length(A) && (r=1:r[length(A)]) else !issubset(r,1:length(A)) && (r=intersect(r,1:length(A))) end for n = r a=combinations(A,n) for i in a push!(o,i) end end return o end subsets(A::AbstractArray) = subsets(A,1:length(A))
它可以列出所有子集或不超过一定限制(长度)的子集:例如:
julia> subsets(1:3) 7-element Array{Array{Int64,1},1}: [1] [2] [3] [1, 2] [1, 3] [2, 3] [1, 2, 3] julia> subsets(1:3,2) 3-element Array{Array{Int64,1},1}: [1, 2] [1, 3] [2, 3]