0

我试图弄清楚如何形成一个数组,该数组收集特定对象的每个索引(在本例中为单个字母),它出现在一组嵌套数组中。例如,使用下面的数组集,

boggle_board = [["P", "P", "X", "A"], 
                ["V", "F", "S", "Z"],
                ["O", "P", "W", "N"],
                ["D", "H", "L", "E"]]

我希望boggle_board.include?("P")返回一个嵌套的索引数组[[0,0][0,1],[2,1]]。关于如何做到这一点的任何想法?

4

2 回答 2

1

我现在没有想到任何超级优雅的东西。这似乎有效:

def indices_of(board, letter)
  indices = []

  board.each_with_index do |ar, i|
    ar.each_with_index do |s, j|
      indices.push([i, j]) if s == letter
    end
  end

  indices
end

boggle_board = [["P", "P", "X", "A"], 
                ["V", "F", "S", "Z"],
                ["O", "P", "W", "N"],
                ["D", "H", "L", "E"]]

indices_of(boggle_board, "P")
# => [[0, 0], [0, 1], [2, 1]]
于 2013-06-07T02:47:22.480 回答
0

我会使用Matrix#each_with_index。下面的代码更 Rubyistic:

require "matrix"
m = Matrix[["P", "P", "X", "A"], 
           ["V", "F", "S", "Z"],
           ["O", "P", "W", "N"],
           ["D", "H", "L", "E"]]
ar = []
m.each_with_index {|e, row, col| ar << [row,col] if e == "P"}
ar #=> [[0, 0], [0, 1], [2, 1]] 
于 2013-06-07T07:44:29.297 回答