Reputation: 2924
For instance, given the input n = 3
I want to obtain:
[(1,),(2,),(3,),(1,2),(1,3),(2,3),(1,2,3)]
I tried a python-like syntax:
combs = [comb for x in collect(1:n) for comb in combinations(collect(1:n),x)]
but I got the following error message:
ERROR: LoadError: syntax: expected ]
I've also tried this:
combs = [comb for comb in vcat([combinations(collect(1:n),x) for x in collect(1:n)])]
but I got:
[Base.Combinations{Array{Int64,1}}([1,2,3],1),Base.Combinations{Array{Int64,1}}([1,2,3],2),Base.Combinations{Array{Int64,1}}([1,2,3],3)]
How to get the result I want?
Upvotes: 2
Views: 774
Reputation: 18217
Is
n = 3
vcat([collect(combinations(1:n,i)) for i=1:n]...)
OK?
Output:
7-element Array{Array{Int64,1},1}:
[1]
[2]
[3]
[1,2]
[1,3]
[2,3]
[1,2,3]
OTHER METHODS:
Another method is [65-findin(bits(i),'1') for i=1:(2^n-1)]
, which points the way to a very efficient implementation along the lines of:
tmp = BitVector(sizeof(Int)*8)
[begin tmp.chunks[1]=i; find(tmp) end for i=1:(2^n-1)]
although it uses BitVector internals, which might be obscure.
For memory efficiency:
using Iterators
chain(([combinations(1:n,i) for i=1:n])...) |> collect
(could be used directly as iterator in a for
loop). But with Iterators
one could use:
drop(subsets(1:n),1) |> collect
which is readable.
Upvotes: 6