Solution: Eight Queens Puzzle
Go over the solution to the eight queens puzzle.
We'll cover the following...
Eight queens puzzle
Press + to interact
def print_chessboard@chessboard.length.times do |i|puts " #{@chessboard[i].join(" | ")}"puts "--- " * @chessboard[i].sizeendend# calculating diagonal valuesdef get_diagonal_values posdiagonals = []len = @chessboard.length@chessboard.length.times do |i|neg_x = pos[0] - ineg_y = pos[1] - ipos_x = pos[0] + ipos_y = pos[1] + idiagonals << @chessboard[neg_x][neg_y] if neg_x >= 0 && neg_y >= 0diagonals << @chessboard[neg_x][pos_y] if neg_x >= 0 && pos_y < lendiagonals << @chessboard[pos_x][neg_y] if neg_y >= 0 && pos_x < lenendreturn diagonalsenddef check_constraints posdiagonals = get_diagonal_values(pos)@chessboard[pos[0]].all? { | x | x == "." } && # no queen in same row@chessboard.collect { | sqr | sqr[pos[1]] }.all? { | x | x == "." } && # no queen in same columndiagonals.all? { | x | x == "." } && # no queen in all diagonals@chessboard[pos[0]][pos[1]] == "." # unvisited locationend@queens = 0@max_queens = 8@chessboard = Array.new(8){ Array.new(8, '.')}def place_queens row@chessboard[row][@queens] = "Q" # placing queen in chessboard@queens += 1# end causeif @queens == @max_queensprint_chessboardexitend# trying all possible locations in a row@chessboard.length.times do |row_item|place_queens(row_item) if check_constraints([row_item, @queens]) # only place queen when constraints are metend# backtracking@queens -= 1@chessboard[row][@queens] = "."end@chessboard.length.times do |x|place_queens(x)end# loop ended without finding a solutionputs "Solution not found!"
Explanation
Instance variables
The role of instance variables in the code (lines 37–39) is:
@chessboard
is initialized to an array of size8
, such that each of its elements is also an array of size8
(representing a chess board row) containing.
characters. ...