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

时间:2014-05-27 20:48:59

标签: 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]

就像我一样

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

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

2 个答案:

答案 0 :(得分: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

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

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

答案 1 :(得分:0)

这不是Julia特有的,但在这种情况下我通常做的是(伪代码):

array = [1, 1, 1, .., 1] # ones n times
while True
  # increased last element by one
  array(end) += 1
  # looking at overflows from end to beginning
  for i = n:-1:2
    if array(i) > m
      array(i) = 1
      array(i-1) += 1
    end
  end
  # if overflow in the first entry, stop
  if array(1) > m
    break
  end
  # do something with array, it contains the indices now
  ..
end