Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Last active November 8, 2015 08:18
Show Gist options
  • Save durrellchamorro/c1c1f42ee802a15a2066 to your computer and use it in GitHub Desktop.
Save durrellchamorro/c1c1f42ee802a15a2066 to your computer and use it in GitHub Desktop.
Queen Attack Solution
class Queens
attr_reader :white, :black
def initialize(white: [0, 3], black: [7, 3])
@white, @black = white, black
fail ArgumentError, "Queens cannot occupy the same position." if white == black
end
def to_s
mark_board.map { |row| row.join(" ") }.join("\n")
end
def attack?
queens_on_same_row? || queens_on_same_column? || queens_on_diagonal?
end
private
def initialize_board
board = []
8.times { board << %w(_ _ _ _ _ _ _ _) }
board
end
def white_queen_row
white.first
end
def white_queen_column
white.last
end
def black_queen_row
black.first
end
def black_queen_column
black.last
end
def mark_board
board = initialize_board
board.fetch(white_queen_row)[white_queen_column] = "W"
board.fetch(black_queen_row)[black_queen_column] = "B"
board
end
def queens_on_same_row?
white_queen_row == black_queen_row
end
def queens_on_same_column?
white_queen_column == black_queen_column
end
def queens_on_diagonal?
(white_queen_row - white_queen_column).abs == (black_queen_row - black_queen_column).abs
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment