Skip to content

Instantly share code, notes, and snippets.

@abhinavnigam2207
Last active June 1, 2021 17:07
Show Gist options
  • Save abhinavnigam2207/6b15ba1af75792238d96d6d6ced00e6e to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/6b15ba1af75792238d96d6d6ced00e6e to your computer and use it in GitHub Desktop.
Eight Queens Problem Coder Byte
// https://www.coderbyte.com/editor/guest:Eight%20Queens:JavaScript
//
// Have the function EightQueens(strArr) read strArr which will be an array
// consisting of the locations of eight Queens on a standard 8x8 chess board
// with no other pieces on the board. The structure of strArr will be the
// following: ["(x,y)", "(x,y)", ...] where (x,y) represents the position of the
// current queen on the chessboard (x and y will both range from 1 to 8 where
// 1,1 is the bottom-left of the chessboard and 8,8 is the top-right). Your
// program should determine if all of the queens are placed in such a way where
// none of them are attacking each other. If this is true for the given input,
// return the string "true" otherwise return the first queen in the list that is
// attacking another piece in the same format it was provided.
//
// For example: if strArr is ["(2,1)", "(4,2)", "(6,3)", "(8,4)", "(3,5)",
// "(1,6)", "(7,7)", "(5,8)"] then your program should return the string true.
// The corresponding chessboard of queens for this input is below (taken from
// Wikipedia).
function eightQueens(strArr) {
let x =[], y =[];
strArr.forEach((pos) => {
x.push(Number(pos.replace('(','').replace(')','').split(',')[0]));
y.push(Number(pos.replace('(','').replace(')','').split(',')[1]));
});
const setX = new Set(x);
const setY = new Set(y);
let flag = true;
let resp = '';
for(let i=0; i < strArr.length; i++) {
for(let j=1; j < strArr.length; j++) {
if(flag && (x[j]-x[i] === y[j]-y[i] || x[i]===x[j] || y[i]===y[j])) {
resp = `(${x[i]},${y[i]})`;
flag = false;
}
}
}
if(x.length === setX && x.length === setY && !resp.length) {
return true;
} else{
return resp;
}
}
console.log(eightQueens(readline()));
@mhaf4krr
Copy link

mhaf4krr commented Jun 1, 2021

Can you please explain the solution ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment