How to nest any number of for loops

I need to iterate over all combinations of k permutations of integers (1:n).

Say, k=2 and n=2.
The permutations of (1:2) are
[1, 2]
[2, 1]

and what i need is
[1, 2] , [1, 2]
[1, 2] , [2, 1]

[2, 1] , [1, 2]
[2, 1] , [2, 1]

In this case (k=2) i can obtain the iterator (using Combinatorics.jl) such as (MWE)

using Combinatorics
n=2
# k=2, 2 nested for loops
P=((a, b) for a in permutations(1:n) for b in permutations(1:n))
foreach(println, P)

How can i generalize this for any positive k?

My first guess would be to go to Base.Cartesian looking for the right macro, these macros are used to construct an arbitrary number of nested loops at compile time. But here maybe you simply need somethign recursive alike the following:

function make(k,n)
    if k == 0
        return 1:n
    else
        return permutations(make(k-1,n))
    end
end

?


EDIT: by the way,

does not correspond to what your code does for k=2, which iterates over permutation(1:n) x permutations(1:n) ? Perhaps you could clarify a bit what you need ?


EDIT: I think I understood what you want, which could be this:

using Base.Iterators
k=2
n=2
for indices in product((permutations(1:n) for i in 1:k)...)
    @show indices
end

which outputs

indices = ([1, 2], [1, 2])
indices = ([2, 1], [1, 2])
indices = ([1, 2], [2, 1])
indices = ([2, 1], [2, 1])

?

The Base.Cartesian.@nloops macro constructs such things.
Take a look at Base.Cartesian · The Julia Language

1 Like

Not beautiful, but does what you ask.

f(n,k)=collect(multiset_permutations(repeat(collect(permutations(1:n)),k),k))

Thanks, this works indeed:

using Combinatorics
n=3
k=2
P=Iterators.product((permutations(1:k) for i in 1:n)...) 
foreach(println, P)

This works, but creates physically the permutations as a vector. I just need an iterator.

Good to know! i’ll check if needed


f(n,k)=multiset_permutations(repeat([permutations(1:n)...],k),k)

k=2
n=2
for p in f(n,k)
    @show p
end

Thanks, this does the job. Just, as i need the (k!)^n permutations, the k and n indices must be interchanged, as for the solution given by @irvn (my bad, my question was not correct). This is what i’ve got:

k=2
n=3
num_of_permutations=(factorial(k)^n)
P = multiset_permutations(repeat([permutations(1:k)...], n) , n)
foreach(println, P)