gpt4 book ai didi

julia - Julia 中 se 的所有子集

转载 作者:行者123 更新时间:2023-12-04 00:28:52 24 4
gpt4 key购买 nike

你能帮帮我吗?我怎样才能做一个可以找到集合的所有子集的代码

例如

我想在 Julia 中编写此约束。这是一个子约束。但我不知道如何找到 S 集的所有子集。

enter image description here

@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);

非常感谢

最佳答案

您可以使用 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]

关于julia - Julia 中 se 的所有子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54052333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com