Created
October 31, 2015 17:58
-
-
Save falonofthetower/ef1bfc7e259a0ec6dce1 to your computer and use it in GitHub Desktop.
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 Board | |
def self.transform(board) | |
@rows = [] | |
explode_rows(board) | |
validate_rows | |
process_rows | |
reform_rows | |
end | |
def self.validate_rows | |
raise ValueError unless rows_the_same_length? | |
raise ValueError unless characters_valid? | |
raise ValueError unless valid_borders? | |
end | |
def self.valid_borders? | |
return false unless @rows.first.first == "+" | |
return false unless @rows.first.last == "+" | |
return false unless @rows.last.first == "+" | |
return false unless @rows.last.last == "+" | |
return false unless @rows.first[1..-2].all? { |character| character == "-" } | |
return false unless @rows.last[1..-2].all? { |character| character == "-" } | |
return false unless @rows[1..-2].first.first == "|" | |
return false unless @rows[1..-2].first.last == "|" | |
return false unless @rows[1..-2].last.first == "|" | |
return false unless @rows[1..-2].last.last == "|" | |
return true | |
end | |
def self.characters_valid? | |
@rows.flatten.all? {|character| %w(+ * | - \ ).include? character } | |
end | |
def self.rows_the_same_length? | |
@rows.all? {|row| row.length == @rows[0].length } | |
end | |
def self.explode_rows(board) | |
board.each do |row| | |
row_array = row.chars | |
@rows << row_array | |
end | |
end | |
def self.process_rows | |
@rows.each_with_index do |row, row_key| | |
row.each_with_index do |character, character_key| | |
unless %w(+ - | *).include?(character) | |
self.set_character_value(character, row_key, character_key) | |
end | |
end | |
end | |
end | |
def self.set_character_value(location, row_key, character_key) | |
above = row_key - 1 | |
below = row_key + 1 | |
right = character_key + 1 | |
left = character_key - 1 | |
total = 0 | |
total += 1 if @rows[above][character_key] == "*" | |
total += 1 if @rows[above][left] == "*" | |
total += 1 if @rows[above][right] == "*" | |
total += 1 if @rows[row_key][left] == "*" | |
total += 1 if @rows[row_key][right] == "*" | |
total += 1 if @rows[row_key][character_key] == "*" | |
total += 1 if @rows[below][character_key] == "*" | |
total += 1 if @rows[below][left] == "*" | |
total += 1 if @rows[below][right] == "*" | |
if total >= 1 | |
@rows[row_key][character_key] = total | |
end | |
end | |
def self.reform_rows | |
@rows.map! {|row| row.join("") } | |
end | |
end | |
class ValueError < StandardError | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment