🦁
全ての部分集合をbit全探索で求める
やりたいこと
2 4 1 4 2
上記の数列に対して、全ての部分集合を求めます。
ソースコード
ary = [2, 4, 1, 4, 2]
n = size(ary, 1)
# 1<<nは、2^5と同じ意味である。
for bit ∈ 0:(1<<n)-1
s = []
for i ∈ 0:length(ary)-1
if bit & 1 << i ≠ 0
push!(s, ary[i+1])
end
end
@show s
end
出力結果
s = Any[]
s = Any[2]
s = Any[4]
s = Any[2, 4]
s = Any[1]
s = Any[2, 1]
s = Any[4, 1]
s = Any[2, 4, 1]
s = Any[4]
s = Any[2, 4]
s = Any[4, 4]
s = Any[2, 4, 4]
s = Any[1, 4]
s = Any[2, 1, 4]
s = Any[4, 1, 4]
s = Any[2, 4, 1, 4]
s = Any[2]
s = Any[2, 2]
s = Any[4, 2]
s = Any[2, 4, 2]
s = Any[1, 2]
s = Any[2, 1, 2]
s = Any[4, 1, 2]
s = Any[2, 4, 1, 2]
s = Any[4, 2]
s = Any[2, 4, 2]
s = Any[4, 4, 2]
s = Any[2, 4, 4, 2]
s = Any[1, 4, 2]
s = Any[2, 1, 4, 2]
s = Any[4, 1, 4, 2]
s = Any[2, 4, 1, 4, 2]
以上となります。
Discussion