Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juandefelix/7400979 to your computer and use it in GitHub Desktop.
Save juandefelix/7400979 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1 boggle class challenge
class BoggleBoard
def initialize(board)
@board = board
end
def create_word(*coords)
coords.map {|coord| @board[coord.first][coord.last]}.join("")
end
def get_row(row)
@board[row] # accessing the row of a 2D array
end
def get_col(col)
# @board.map {|row| row[col]} #more traditional and less fancy way to do it
@board.transpose[col] #transpose rotates the 2d array. The rows become columns and viceversa
end
def get_char(loc)
@board[loc.first][loc.last] # accessing an element in a 2D array
end
# def get_diagonal loc # UNREFACTORED METHOD
# coords =[loc]
# x = loc.first; y = loc.last
# while x<@board.size-1 && y<@board.size-1 #while the values don't reach the end of the board
# x += 1; y +=1
# coords << [x,y] #add a location to the array that is one row greather and one column greather
# end
# coords.map{|loc| get_char loc}.join #pass that array to create_word
# end
def get_diagonal coord
coords = (0..@board.size-1).map{|x| [coord[0] + x, coord[1] + x]} # create an array of coords incrementing by one the indices of rows and columns
coords.delete_if{|x| x.any?{|val| val>= @board.size}} # remove the coordenates that exceed the boundaries of the board
create_word *coords # using existing method for accessing some coords (DRYness)
end
end
dice_grid = [["b", "r", "a", "e"],
["i", "o", "d", "t"],
["e", "c", "l", "r"],
["t", "a", "k", "e"]]
b = BoggleBoard.new(dice_grid)
# implement tests for each of the methods here:
puts "get_char tests:"
puts b.get_char([3,2]) == 'k'
puts b.get_char([1,1]) == 'o'
puts
puts "create_word tests:"
puts (b.create_word [2,1],[1,1],[1,2],[0, 3]) == "code"
puts (b.create_word [0,1], [0,2], [1,2]) == "rad"
puts (b.create_word [0,0], [1,1], [2,2], [1,2]) == "bold"
puts (b.create_word [3,0], [3,1], [3,2], [3,3]) == "take"
puts (b.create_word [1,2], [1,1], [2,1], [3,2]) == "dock"
puts
puts "get_row tests:"
puts b.get_row(0) == ["b", "r", "a", "e"]
puts b.get_row(2) == ["e", "c", "l", "r"]
puts
puts "get_col tests:"
puts b.get_col(1) == ["r", "o", "c", "a"]
puts b.get_col(2) == ["a", "d", "l", "k"]
puts b.get_col(0) == ['b', 'i', 'e', 't']
puts
puts "get_diagonal tests:"
puts b.get_diagonal([0,0]) == 'bole'
puts b.get_diagonal([1,2]) == 'dr'
# REFLECTIONS
# I found VERY USEFUL the use of *array.
# This simbol comverts an array (one object) in several object containing the elements in the array.
# In #get_diagonal I refactored a more traditional code using ranges,arrays methods and blocks.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment