Skip to content

Instantly share code, notes, and snippets.

@rugyoga
Created July 27, 2019 19:07
Show Gist options
  • Save rugyoga/99cb135f15da2556eb9cc6bfa9013bac to your computer and use it in GitHub Desktop.
Save rugyoga/99cb135f15da2556eb9cc6bfa9013bac to your computer and use it in GitHub Desktop.
N Queens solutions using counts
class NQueensCounts < NQueens
def initialize(size)
super(size)
@attacks =
Array.new(size) do |file|
Array.new(size) { |rank| attacks_all(file, rank) }
end
@counts = Array.new(size) { Array.new(size) { 0 } }
end
def attacks(squares, file, rank, file_delta, rank_delta)
file += file_delta
rank += rank_delta
while file >= 0 && file < @size &&
rank >= 0 && rank < @size
squares << [file, rank]
file += file_delta
rank += rank_delta
end
end
def attacks_all(file, rank)
squares = [[file, rank]]
[[1, 0], [0, 1], [1, 1], [-1, 1]].each do |file_delta, rank_delta|
attacks(squares, file, rank, file_delta, rank_delta)
attacks(squares, file, rank, -file_delta, -rank_delta)
end
squares
end
def move!(file, rank)
super(file, rank)
@attacks[file][rank].each { |f, r| @counts[f][r] += 1 }
end
def unmove!(file, rank)
super(file, rank)
@attacks[file][rank].each { |f, r| @counts[f][r] -= 1 }
end
def unsafe?(file, rank)
@counts[file][rank].positive?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment