Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save j55d/9065706 to your computer and use it in GitHub Desktop.
Save j55d/9065706 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1boggle 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]
end
def get_col(col)
@board.transpose[col] # changes the columns to rows, then outputs the new row
# ([email protected]).map{|row| @board[row][col]} #map is also pretty concise
end
end
def get_diagonal(coord1, coord2)
raise ArgumentError if (coord1[0] - coord2[0]).abs != (coord1[1] - coord2[1]).abs # raises an error if the coordinates do not form a diagonal
coord1, coord2 = coord2, coord1 if coord1[0] > coord2[0] # the coordinates should be top-to-bottom. This switches them if not.
if coord1 == coord2
@board[coord1[0]][coord1[1]] # if the diagonal is a single element, it returns that element
elsif coord2[1] > coord1[1] # right-to-left diagonal
(0..(coord2[0] - coord1[0])).collect{|i| @board[coord1[0]+i][coord1[1]+i]}
elsif coord2[1] < coord1[1] # left-to-right diagonal
(0..(coord2[0] - coord1[0])).collect{|i| @board[coord1[0]+i][coord1[1]-i]}
end
end
end
dice_grid = [["b", "r", "a", "e"],
["i", "o", "d", "t"],
["e", "c", "l", "r"],
["t", "a", "k", "e"]]
boggle = BoggleBoard.new(dice_grid)
p boggle.create_word([2,1], [1,1], [1,2], [0,3]) == "code" # should all return true
p boggle.create_word([0,1], [0,2], [1,2]) == "rad"
p boggle.create_word([1,3], [0,2], [0,1],[1,1]) == "taro"
p boggle.create_word([3,0], [3,1], [2,1],[1,1]) == "taco"
p boggle.get_row(1) == ["i", "o", "d", "t"]
p boggle.get_row(3) == ["t", "a", "k", "e"]
p boggle.get_col(2) == ["a", "d", "l", "k"]
p boggle.get_col(0) == ["b", "i", "e", "t"]
p boggle.get_diagonal([0,3],[3,0]) == ["e", "d", "c", "t"]
p boggle.get_diagonal([0,1],[2,3]) == ["r", "d", "r"]
p dice_grid[3][2] == "k"
p dice_grid[0][3] == "e"
# Reflect
# After the first boggle exercise I learned about the #transpose method and was able to refactor #get_col
#
# I hit a couple stumbling blocks with #get_diagonal. At first I didn't take into account left-to-right diagonals,
# so coordinates such as [0,3], [3,0] did not return a correct answer. I wasn't sure whether only use one elsif statement
# and insert a sign variable (negative if left-to-right, positive otherwise), but decided to just make two elsif statements.
#
#
#
#
#
#
#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment