Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save parthnaik/9448694 to your computer and use it in GitHub Desktop.
Save parthnaik/9448694 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1boggle class challenge
class BoggleBoard
attr_reader :grid
def initialize(grid)
@grid = grid
raise ArgumentError.new("length of each row must be equal") if (grid.any? {|row| row.length != grid[0].length})
end
def create_word(*coords) # creates a word based on given coordinates
coords.map {|coord| @grid[coord.first][coord.last]}.join("")
end
def get_row(row)
@grid[row]
end
def get_col(col)
@grid.map { |row| row[col] }
end
def access(x, y)
@grid[x][y]
end
# the diagonal check can be performed by checking if the difference b/w the x coord and the y coord is equal
def get_diagonal(coord1, coord2)
start1 = coord1[0]
start2 = coord1[1]
finish1 = coord2[0]
finish2 = coord2[1]
raise ArgumentError.new("not valid diagonal coordinates") if ((finish1 - start1).abs != (finish2 - start2).abs)
if start1 < finish1 && start2 < finish2 #SE
until start1 == finish1 + 1
p @grid[start1][start2]
start1 +=1
start2 +=1
end
elsif start1 > finish1 && start2 > finish2 #NW
until start2 == finish2 - 1
p @grid[start1][start2]
start1 -=1
start2 -=1
end
elsif start1 > finish1 && start2 < finish2 #NE
until start2 == finish2 + 1
p @grid[start1][start2]
start1 -=1
start2 +=1
end
elsif start1 < finish1 && start2 > finish2 #SW
until start1 == finish1 + 1
p @grid[start1][start2]
start1 +=1
start2 -=1
end
end
end
end
dice_grid = [["b", "r", "a", "e"],
["i", "o", "d", "t"],
["e", "c", "l", "r"],
["t", "a", "k", "e"]]
boggle_board = BoggleBoard.new(dice_grid)
# implement tests for each of the methods here:
boggle_board = BoggleBoard.new(dice_grid)
puts boggle_board.create_word([1,2], [1,1], [2,1], [3,2])
print boggle_board.get_row(1)
puts ""
print boggle_board.get_col(1)
puts ""
# create driver test code to retrieve a value at a coordinate here:
puts boggle_board.access(3, 3)
puts boggle_board.get_diagonal([0, 3], [3, 0])
# Reflection:
# Some tips:
# Make sure you compare absolute value of differences (line 32), otherwise Up-Right and Down-Left diagonals won't work
# There are 4 cases for the diagonal, each one took me considerable time but I got it eventually.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment