Skip to content

Instantly share code, notes, and snippets.

@FermiDirak
Created October 13, 2019 04:11
Show Gist options
  • Save FermiDirak/0ff4239049cb5a1d290a92e267925ed2 to your computer and use it in GitHub Desktop.
Save FermiDirak/0ff4239049cb5a1d290a92e267925ed2 to your computer and use it in GitHub Desktop.
var queensAttacktheKing = function(queens, king) {
function inBounds([x, y]) {
return x >= 0 && x < 8 && y >= 0 && y < 8;
}
function isQueen([x, y]) {
return queens.some(queen => {
return queen[0] === x && queen[1] === y;
});
}
const dirs = [
[ 0, -1],
[ 1, -1],
[ 1, 0],
[ 1, 1],
[ 0, 1],
[-1, 1],
[-1, 0],
[-1, -1],
];
const res = [];
dirs.forEach(dir => {
let pos = king.slice(0);
while (true) {
pos = [pos[0] + dir[0], pos[1] + dir[1]];
if (!inBounds(pos)) {
return;
}
if (isQueen(pos)) {
res.push(pos);
return;
}
}
});
return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment