Forked from dbc-challenges/0.2.1-boggle_class_from_methods.rb
Last active
December 27, 2015 17:39
-
-
Save qsymmachus/7363874 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1
boggle class challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BoggleBoard | |
attr_reader :board | |
def initialize(board) | |
@board = board | |
end | |
def create_word(*coords) | |
coords.map { |coord| @board[coord.first][coord.last]}.join("") | |
end | |
def get_row(row) | |
return @board[row-1].inspect | |
end | |
def get_col(col) | |
column = [] | |
@board.each{ |nested| column << nested[col-1] } | |
return column.inspect | |
end | |
def get_diagonal(start_coord, stop_coord) | |
# pass clones to .diagonal so it doesn't alter our coordinates. | |
unless diagonal?(start_coord.clone, stop_coord.clone) | |
raise ArgumentError.new("Start and stop coordinates are not diagonal.") | |
end | |
diagonal = [] | |
while start_coord[0] <= stop_coord[0] | |
diagonal << @board[start_coord.first][start_coord.last] | |
start_coord[0] += 1 | |
start_coord[1] += 1 | |
end | |
return diagonal.inspect | |
end | |
private | |
# Checks if two coordinates are diagonal to one another. | |
def diagonal?(start_coord, stop_coord) | |
while start_coord[0] <= stop_coord[0] | |
return true if start_coord == stop_coord | |
start_coord[0] += 1 | |
start_coord[1] += 1 | |
end | |
false | |
end | |
end | |
#------DRIVERS------ | |
dice_grid = [["b", "r", "a", "e"], | |
["i", "o", "d", "t"], | |
["e", "c", "l", "r"], | |
["t", "a", "k", "e"]] | |
my_board = BoggleBoard.new(dice_grid) | |
puts my_board.create_word([3,0], [3,1], [3,2], [3,3]) #=> returns "take" | |
puts my_board.get_row(2) #=> returns ["i", "o", "g", "t"] | |
puts my_board.get_col(4) #=> returns ["e", "t", "r", "e"] | |
# total output: | |
# brae, iodt, eclr, take | |
# biet, roca, adlk, etre | |
puts my_board.board[3][2] #=> returns "k" | |
puts my_board.get_diagonal([0,0], [3,3]) #=> returns ["b", "o", "l", "e"] | |
#------REFLECTION------ | |
# I was really stumped for a while with my .get_diagonal method because it kept returning only the | |
# final coordinate: | |
# | |
# puts my_board.get_diagonal([0,0], [3,3]) #=> ["e"] | |
# | |
# Finally I realized what the problem was: my .diagonal? method was incrementing my coordinate values, | |
# so once I got to the meat and potatoes of .get_diagonal, my start_coord had been change from [0,0] | |
# to [3,3]! What a goofy mistake. I solved the problem by using .clone to pass copies of my coordinates | |
# to .diagonal? . |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment