Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rwoodnz/9800703 to your computer and use it in GitHub Desktop.
Save rwoodnz/9800703 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1boggle class challenge
class BoggleBoard
attr_accessor :board
def initialize(dice_grid)
@board = dice_grid
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]
end
def get_diag(start, finish)
distance = (finish.first - start.first).abs
if distance != (finish.last - start.last).abs then
raise ArgumentError, "This is not a diagonal"
end
row_start = start.first
row_increment = (finish.first - start.first)/(finish.first - start.first).abs
col_start = start.last
col_increment = (finish.last - start.last)/(finish.last-start.last).abs
(0..distance).map { |i| board[row_start+i*row_increment][col_start+i*col_increment] }
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:
p boggle_board.create_word([2,1], [1,1], [1,2], [0,3]) == "code"
p boggle_board.create_word([0,1], [0,2], [1,2]) == "rad"
p boggle_board.create_word([1,3], [2,3], [3,3], [3,2]) == "trek"
p boggle_board.create_word([3,0], [3,1], [3,2], [3,3]) == "take"
p boggle_board.get_row(1) == ["i", "o", "d", "t"]
p boggle_board.get_row(2) == ["e", "c", "l", "r"]
p boggle_board.get_row(3) == ["t", "a", "k", "e"]
p boggle_board.get_col(1) == ["r", "o", "c", "a"]
p boggle_board.get_col(2) == ["a", "d", "l", "k"]
# output from tests:
# true
# true
# true
# true
# true
# true
# true
# true
# true
# each row and each column:
(0..dice_grid.length-1).map {|row| puts boggle_board.get_row(row).join}
(0..dice_grid.first.length-1).map { |col| puts boggle_board.get_col(col).join}
# test output:
# brae
# iodt
# eclr
# take
# biet
# roca
# adlk
# etre
# create driver test code to retrieve a value at a coordinate here:
p boggle_board.get_row(3)[2] == "k"
# output
# true
# get diagonal
p boggle_board.get_diag([3,2], [1,0]) == ["k", "c", "i"]
# output
# true
# Reflection
# A class acts as a template allowing us to create unlimited board objects that we can send around
# and can keep related code together with its data making it less interdependent with other code and data
# In this example object oriented programming ensures the board data is
# available to the functions without making it directly accessible outside the object, or inside for that matter.
# that makes the code more maintainable and more DRY. If we want to change the way data is managed we can
# do it in one spot and the calls do not need to be changed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment