Forked from dbc-challenges/0.2.1-boggle_class_from_methods.rb
Last active
December 29, 2015 05:29
-
-
Save alexcodreanu86/7622694 to your computer and use it in GitHub Desktop.
phase 0 unit 2 week 1
boggle class challenge
This file contains 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) | |
@board[row] # returns a certain element(row) of the array | |
end | |
def get_col(col) | |
@board.map{|row| row[col]} #returns n-th (col) element in each row | |
end | |
def rows_and_cols | |
@board.each_with_index {|row,i| puts "Row #{i} is: #{row.join("")}"} #returns each row joined | |
@board.length.times{|x| puts "Col #{x} is: #{self.get_col(x).join("")}"} #returns each col joined | |
end | |
def get_diagonal(coord1, coord2) | |
unless (coord1[1] - coord2[1]).abs == (coord1[0] - coord2[0]).abs && coord1[1] - coord2[1] != 0 | |
raise ArgumentError , "[#{coord1},#{coord2}] are not coordinates for a diagonal." # if coordonates do not indicate a corner raising an error | |
else | |
diagonal = [] | |
until coord1[1] == coord2[1] && coord1[0] == coord2[0] | |
diagonal << @board[coord1[0]][coord1[1]] | |
if coord1[0] < coord2[0] | |
coord1[0] += 1 | |
if coord1[1] < coord2[1] | |
coord1[1] += 1 | |
else | |
coord1[1] -= 1 | |
end | |
else | |
coord1[0] -= 1 | |
if coord1[1] < coord2[1] | |
coord1[1] += 1 | |
else | |
coord1[1] -= 1 | |
end | |
end | |
end | |
diagonal << @board[coord2[0]][coord2[1]] | |
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], [3,1], [3,2], [3,3]) #=> "cake" | |
p boggle_board.get_row(1) #=> ["i", "o", "d", "t"] | |
p boggle_board.get_col(1) #=> ["r", "o", "c", "a"] | |
boggle_board.rows_and_cols | |
p boggle_board.get_diagonal([0,3],[3,0]) #=> ["e", "d", "c", "t"] | |
p boggle_board.get_diagonal([0,0][3,3]) #=> ["b", "o", "l", "e"] | |
# create driver test code to retrieve a value at a coordinate here: | |
p boggle_board.board[3][2] == "k" #=> should be true | |
# Reflections | |
# The main benefit in OOP that I have noticed is the scope of the instance variables. Available to all the instance methods but in | |
# the same time different and private variables for each object instantiated.Also the private and public feature is very useful protecting some | |
# data from the users... | |
# | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment