Skip to content

Instantly share code, notes, and snippets.

@IrhaAli
Created October 15, 2022 16:13
Show Gist options
  • Save IrhaAli/22d71cca80d6794507bb58fe728ab9de to your computer and use it in GitHub Desktop.
Save IrhaAli/22d71cca80d6794507bb58fe728ab9de to your computer and use it in GitHub Desktop.
Tells whether a queen and attack one another based on the position given
const generateBoard = function (whiteQueen, blackQueen){
//for the love of all that is holy, why is js so ridiculously unintuitive?!?!...how hard is it to create a nxn matrix
let chessBoard = [];
for (let i = 0; i < 8; i++){
if ((whiteQueen[0] !== i) && (blackQueen[0] !== i)){
chessBoard.push(Array(8).fill(0));
}else if (whiteQueen[0] === i){
chessBoard.push(Array(8).fill(0));
chessBoard[i][whiteQueen[1]] = 1;
}else {
chessBoard.push(Array(8).fill(0));
chessBoard[i][blackQueen[1]] = 1;
}
}
/* This is how I had originally planned to create the chessboard but it modifies each row instead of the one index where I need the value 1.
let chessBoard = Array(8).fill(Array(8).fill(0));
chessBoard[whiteQueen[0]].splice(whiteQueen[1],1,1);
chessBoard[blackQueen[0]].splice(blackQueen[1],1,1);
*/
return chessBoard;
}
const queenThreat = function (generatedBoard){
let queensPositions = [];
for (let i = 0; i < generatedBoard.length; i++){
let row = generatedBoard[i].join('');
let pos1 = row.indexOf('1');
let pos2 = row.lastIndexOf('1');
//if both queens lie on the same row
if ((pos1 !== -1) && (pos1 !== pos2)){
return true;
}else if (pos1 !== -1){
queensPositions.push([i,pos1]);
}
}
//if both queens lie on the same column
if (queensPositions[0][1] === queensPositions[1][1]){
return true;
}
//if both queens lie on the same diagonal
let pos1Sum = queensPositions[0][0]+queensPositions[0][1];
let pos2Sum = queensPositions[1][0]+queensPositions[1][1];
let pos1Diff = Math.abs(queensPositions[0][0]-queensPositions[0][1]);
let pos2Diff = Math.abs(queensPositions[1][0]-queensPositions[1][1]);
if ((pos1Sum === pos2Sum) || (pos1Sum === pos2Diff) || (pos2Sum === pos1Diff)){
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment