# How to do permutations with repetition?

Hi there,

Looking to get some ideas on the best approach to doing permutations with repetition please. If I have an array with {x,y,z,…} distinct elements and want to generate all permutations to a length of N allowing repetition, how would I be best to go about doing this?

Thanks

Are you looking for a product iterator?

``````julia> vec(collect(Base.Iterators.product(Base.Iterators.repeated(1:3, 3)...)))
27-element Vector{Tuple{Int64, Int64, Int64}}:
(1, 1, 1)
(2, 1, 1)
(3, 1, 1)
(1, 2, 1)
(2, 2, 1)
(3, 2, 1)
(1, 3, 1)
(2, 3, 1)
(3, 3, 1)
(1, 1, 2)
(2, 1, 2)
(3, 1, 2)
(1, 2, 2)
(2, 2, 2)
(3, 2, 2)
(1, 3, 2)
(2, 3, 2)
(3, 3, 2)
(1, 1, 3)
(2, 1, 3)
(3, 1, 3)
(1, 2, 3)
(2, 2, 3)
(3, 2, 3)
(1, 3, 3)
(2, 3, 3)
(3, 3, 3)
``````

This appears to be exactly what I need, thanks.

The “…” notation threw me off a bit because I haven’t seen it in a programming language before I don’t think, but I’ve given the command a run and it appears to be working for me.

By the way, `Iterators` is exported, so you can write `Iterators.product` instead of `Base.Iterators.product`, etc.

Another perspective is that this is like counting in base three:

``````julia> [digits(x - 1, base=3, pad=3) .+ 1 for x in 1:3^3]
27-element Vector{Vector{Int64}}:
[1, 1, 1]
[2, 1, 1]
[3, 1, 1]
[1, 2, 1]
[2, 2, 1]
[3, 2, 1]
[1, 3, 1]
[2, 3, 1]
[3, 3, 1]
[1, 1, 2]
⋮
[3, 3, 2]
[1, 1, 3]
[2, 1, 3]
[3, 1, 3]
[1, 2, 3]
[2, 2, 3]
[3, 2, 3]
[1, 3, 3]
[2, 3, 3]
[3, 3, 3]
``````

vec(collect(Base.Iterators.product(Base.Iterators.repeated(1:3, 3)…)))

Is there any way to modify the above code to return the result in a Vector instead of a Tuple?

The way I use the code looks like such:

``````arr_values = [0.6, 2.3]
result = vec(collect(Iterators.product(Iterators.repeated(arr_values, length(arr))...)))
``````

Alternatively, could the other syntax you shared ( [digits(x - 1, base=3, pad=3) .+ 1 for x in 1:3^3] ), be modified to support me using my arr_values for the permutations instead of a straight order of consecutive numbers like 1:3. I’ve got the below code and it’s giving me an “ERROR: syntax: invalid iteration specification”:

``````arr_values = [0.6,2.3]
res = [digits(x-1, base=3, pad=3) for .+ 1 for x in (arr_values)^3]
``````

Is there a reason `vec` doesn’t have a method operating on `Tuple`s?

``````Base.vec(t::Tuple) = [t...]
vec(map(vec, Iterators.product(Iterators.repeated(1:3, 3)...)))
``````