0

I am trying to figure out how to form an array that collects every index of a particular object (in this case a single letter) where it appears in a nested set of arrays. For instance, using the array set below,

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

I would expect something like boggle_board.include?("P") to return a nested array of indices [[0,0][0,1],[2,1]]. Any ideas on how to do this?

2 Answers 2

1

Nothing super-elegant comes to mind for me right now. This seems to work:

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]] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This is much nicer than the solution I came up with. Involved nested while loops...ugh.
@tlewin Thanks for fixing that typo. ;)
0

I would use Matrix#each_with_index.The below code is more 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]] 

1 Comment

@Pavlov's_Dawg you can take a look at mine also.. :) Ruby supports matrix kind of calculations. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.