All Vectors with Entries from a Given Array

Hey!

I have the following question: Given an array of numbers, say A = [0, 1, 3], what is the best way to get all vectors (arrays) of fix length with entries from A? So in other words, I want to get all vectors from the cartesian product A x ... x A.

I would be happy for any answers! (:

Hi!

You can use Combinatorics.jl for this purpose:

julia> using Pkg;

julia> Pkg.add("Combinatorics");

julia> using Combinatorics;

julia> collect(permutations([0,1,3]))
6-element Array{Array{Int64,1},1}:
 [0, 1, 3]
 [0, 3, 1]
 [1, 0, 3]
 [1, 3, 0]
 [3, 0, 1]
 [3, 1, 0]

I’ve seen the Combinatorics package before, but that’s not exactly what I was looking for; I also want to obtain arrays in which elements of A are contained more than once; for example [0, 0, 0], [0, 0, 1], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 3] etc.

So the number of arrays should be lenght(A)^dimension.

Did you check Base.Iterators.product?

julia> A = [1, 2];

julia> collect(Base.Iterators.product(A, A))
2×2 Array{Tuple{Int64,Int64},2}:
 (1, 1)  (1, 2)
 (2, 1)  (2, 2)

Then this might help:

julia> collect(Combinatorics.with_replacement_combinations([0,1,3],3))
10-element Array{Array{Int64,1},1}:
 [0, 0, 0]
 [0, 0, 1]
 [0, 0, 3]
 [0, 1, 1]
 [0, 1, 3]
 [0, 3, 3]
 [1, 1, 1]
 [1, 1, 3]
 [1, 3, 3]
 [3, 3, 3]

Although this doesn’t satisfy length(A)^dimension. Or as mforets has mentioned:

julia> a = [0,1,3]

julia> collect(Iterators.product(a,a,a))
3×3×3 Array{Tuple{Int64,Int64,Int64},3}:
[:, :, 1] =
 (0, 0, 0)  (0, 1, 0)  (0, 3, 0)
 (1, 0, 0)  (1, 1, 0)  (1, 3, 0)
 (3, 0, 0)  (3, 1, 0)  (3, 3, 0)

[:, :, 2] =
 (0, 0, 1)  (0, 1, 1)  (0, 3, 1)
 (1, 0, 1)  (1, 1, 1)  (1, 3, 1)
 (3, 0, 1)  (3, 1, 1)  (3, 3, 1)

[:, :, 3] =
 (0, 0, 3)  (0, 1, 3)  (0, 3, 3)
 (1, 0, 3)  (1, 1, 3)  (1, 3, 3)
 (3, 0, 3)  (3, 1, 3)  (3, 3, 3)


Thanks, that’s what I was looking for!

Hey!

I have a follow-up question: I want to have the dimension of the vectors as a parameter, like I do not want to write five times A as an input in collect(Base.Iterators.product(A, A, A, A, A)), and the dimension should be variable. How can I achieve this?

Best,
python15

Something like

Base.Iterators.product(ntuple(_ -> A, Val(N))...)

The function that implements it should use value types if possible.

3 Likes