combinationsjulia

All possible combinations of indices in an array, as in nested multiple loops


There is an array [1, 2, ..., m], and there is an integer n.

If m=2 and n=3, I want to obtain

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

It's like I do

for i=1:m
  for j=1:m
    for k=1:m
      \\ get [i, j, k]
    end
  end
end

But, both m and n are variables. How can I do this? I'm using Julia, but any general advice would be fine.


Solution

  • It's not clear to me what you mean by "I want to obtain" and \\ get [i, j, k], but you may find this useful/interesting.

    julia> using Iterators
    
    julia> collect(product(repeated(1:2,3)...))
    8-element Array{(Int32,Int32,Int32),1}:
     (1,1,1)
     (2,1,1)
     (1,2,1)
     (2,2,1)
     (1,1,2)
     (2,1,2)
     (1,2,2)
     (2,2,2)
    
    julia> A=reshape(1:8,(2,2,2))
    2x2x2 Array{Int32,3}:
    [:, :, 1] =
     1  3
     2  4
    
    [:, :, 2] =
     5  7
     6  8
    
    julia> for i in product(repeated(1:2,3)...)
             @show A[i...]
           end
    A[i...] => 1
    A[i...] => 2
    A[i...] => 3
    A[i...] => 4
    A[i...] => 5
    A[i...] => 6
    A[i...] => 7
    A[i...] => 8
    
    julia> cartesianmap((k...)->println(A[k...]^2+1),tuple(repeated(2,3)...))
    2
    5
    10
    17
    26
    37
    50
    65
    

    or even without the Iterators package ...

    julia> cartesianmap((k...)->println(A[k...]),tuple(repmat([2],3)...))
    1
    2
    3
    4
    5
    6
    7
    8