如何查找数组的所有可能索引

Dou*_*oug -2 ruby multidimensional-array

假设我们有一个具有这种形状的数组:[2, 5].可能的指数组合是:

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

如果数组有n维度,有没有一种简单的方法在Ruby中生成索引?

Ste*_*fan 5

这应该工作:

def coordinates(first, *others)
  (0...first).to_a.product(*others.map { |to| (0...to).to_a })
end

coordinates(2, 5)
#=> [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],
#    [1, 0], [1, 1], [1, 2], [1, 3], [1, 4]]

coordinates(4, 3, 3)
#=> [[0, 0, 0], [0, 0, 1], [0, 0, 2],
#    [0, 1, 0], [0, 1, 1], [0, 1, 2],
#    [0, 2, 0], [0, 2, 1], [0, 2, 2],
#    [1, 0, 0], [1, 0, 1], [1, 0, 2],
#    [1, 1, 0], [1, 1, 1], [1, 1, 2],
#    [1, 2, 0], [1, 2, 1], [1, 2, 2],
#    [2, 0, 0], [2, 0, 1], [2, 0, 2],
#    [2, 1, 0], [2, 1, 1], [2, 1, 2],
#    [2, 2, 0], [2, 2, 1], [2, 2, 2],
#    [3, 0, 0], [3, 0, 1], [3, 0, 2],
#    [3, 1, 0], [3, 1, 1], [3, 1, 2],
#    [3, 2, 0], [3, 2, 1], [3, 2, 2]]
Run Code Online (Sandbox Code Playgroud)