数组中索引的所有可能组合,如嵌套的多个循环

Cha*_*ang 5 combinations julia

有一个数组[1, 2, ..., m],有一个整数n.

如果m=2n=3,我想获得

[1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 2, 2]
[2, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 2, 2]
Run Code Online (Sandbox Code Playgroud)

就像我一样

for i=1:m
  for j=1:m
    for k=1:m
      \\ get [i, j, k]
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,无论是mn是变量.我怎样才能做到这一点?我正在使用Julia,但任何一般建议都没问题.

ric*_*2hs 5

我不清楚"我想要获得"是什么意思\\ get [i, j, k],但你可能会觉得这很有用/有趣.

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
Run Code Online (Sandbox Code Playgroud)

甚至没有Iterators包裹......

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