バイナリ・コンビネーション
R の e1071::bincombinations() に相当するもの。
絶対にお勧めではないが,単純で忘れにくいもの。小さな場合に。
julia> [[x,y,z] for x=0:1 for y=0:1 for z=0:1]
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]
多分,実際にメモリ内に確保してしまうもの。
julia> all_perm(x, n) = vec(map(collect, Iterators.product(ntuple(_ -> x, n)...)))
julia> all_perm([0, 1], 4)
[0, 0, 0, 0]
[1, 0, 0, 0]
[0, 1, 0, 0]
[1, 1, 0, 0]
:略
[0, 1, 1, 1]
[1, 1, 1, 1]
julia> for i in all_perm(["a", "b"], 3)
println(i)
end
["a", "a", "a"]
["b", "a", "a"]
["a", "b", "a"]
["b", "b", "a"]
["a", "a", "b"]
["b", "a", "b"]
["a", "b", "b"]
["b", "b", "b"]
たぶん,iterator を使って上手くやるもの。
julia> all_perm(x, n) = Iterators.product([x for i = 1:n]...)
julia> for i in all_perm([0, 1], 3)
println(i)
end
(0, 0, 0)
(1, 0, 0)
(0, 1, 0)
(1, 1, 0)
(0, 0, 1)
(1, 0, 1)
(0, 1, 1)
(1, 1, 1)
組み合わせ
R の combn() に相当するもの。
julia> using Combinatorics
julia> for i in combinations(1:4, 2)
println(i)
end
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
julia> for i in combinations(["one", "two", "three", "four"], 2)
println(i)
end
["one", "two"]
["one", "three"]
["one", "four"]
["two", "three"]
["two", "four"]
["three", "four"]
順列
R の permutations() に相当するもの。
多分,メモリに確保してしまうもの。
julia> for i in permutations([1,2,3])
println(i)
end
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
多分,iterator で上手くやってくれるもの。
julia> a = [1,2,3]
julia> for i in 1:factorial(length(a))
println(nthperm(a, i))
end
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
nthperm!() は破壊的なので,全ての順列を網羅できない。
網羅しなくても良い場合や,重複しても良い場合はこちらが多分よいはず。
julia> a = [1,2,3]
julia> for i in 1:factorial(length(a))
println(nthperm!(a, i))
end
[1, 2, 3]
[1, 3, 2]
[3, 1, 2]
[1, 2, 3]
[3, 1, 2]
[2, 1, 3]
※コメント投稿者のブログIDはブログ作成者のみに通知されます