2

我有一个多维数组:

foo = [["a","b","c"], ["d", "e", "f"], ["g", "h", "i"]]

现在我需要计算“f”的“坐标”,它应该是(1,2)。在不知道哪个“行”“f”在的情况下,我怎么能做到这一点?我一直在尝试使用 index 方法,但这仅在我告诉它在哪里查找时才有效,即

foo[1].index("f")  #=>2

我尝试了类似的东西

foo[0..2][0..2].index("f")

但这只是返回零。

这可能吗?

4

5 回答 5

4

循环遍历数组的索引并在找到所需内容时返回当前路径。这是一个示例方法:

def find2d(array, elem)
  array.each_with_index do |row, row_idx|
    row.each_with_index do |col, col_idx|
      return [row_idx, col_idx] if col == elem
    end
  end
end
于 2009-02-14T18:20:54.900 回答
3
foo.each_with_index do |item, index|
  if item.index('f')
    // the array number that 'f' is in
    puts "Array number: #{index}"
    // the index in that array of the letter 'f'
    puts item.index('f')
  end
end
于 2009-02-14T18:19:33.360 回答
1

您可能需要遍历数组以找到字母,然后打印出位置。

这更像是一个通用的代码片段,而不是真正的 ruby​​。但是这个概念是存在的。不过不知道有没有更好的办法。

for(int i = 0; i < 3; i++ ) {
 for(int x = 0; i < 3; x++ ) {
  if( foo[i][x] == 'f' ) {
   print x, i;
  }
 }
}
于 2009-02-14T18:06:22.983 回答
1

另一种方式,仅供娱乐:

y = nil
x = (0...foo.size).find {|xi| y = foo[xi].index("f")}

“y=nil”部分只是在循环之前定义了“y”,所以你可以在之后阅读它......

于 2009-02-14T19:57:55.323 回答
0

您可以使用

foo.flatten

得到一个展平的数组,然后使用索引

于 2009-02-14T18:07:12.467 回答