Created
June 25, 2015 14:46
-
-
Save travisp/57cfb865db5a4f61e135 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 QueenCheck | |
def self.safe_moves(q, k) | |
z=->(p){q[0]==p[0]||q[1]==p[1]||(-7..7).map{|d|q.map{|x|x+d}}.include?(p)};z[k]?(t=[-1,0,1]).product(t).count{|a,b|(c=[k[0]+a,k[1]+b]).all?{|x|(1..8)===x}&&!z[c]}:-1 | |
end | |
def self.safe_moves_explanation(queen_coords, king_coords) | |
is_check = -> (king_coords) { | |
return true if queen_coords[0] == king_coords[0] || queen_coords[1] == king_coords[1] | |
(-7..7).map do |diagonal_move| | |
[queen_coords[0] + diagonal_move, queen_coords[1] + diagonal_move] | |
end.include?(king_coords) | |
} | |
return -1 unless is_check[king_coords] | |
[-1,0,1].product([-1,0,1]).map do |move| | |
[king_coords[0] + move[0], king_coords[1] + move[1]] | |
end.count { |moved_coords| | |
valid = moved_coords.all? { |coord| coord.between?(1,8)} | |
valid && !is_check[moved_coords] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment