Last active
July 23, 2024 12:18
-
-
Save animesh-chouhan/5b9f2f9ae585a4dc224fd2fc626efa67 to your computer and use it in GitHub Desktop.
JavaScript code to solve the LinkedIn Queens puzzle using chrome devtools
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
const N = Math.sqrt(document.querySelector("#queens-grid").children.length) | |
// Parse the grid into 2D color array | |
var arr = Array.from(Array(N), () => new Array(N)); | |
for (let i = 0; i < N; i++) { | |
for (let j = 0; j < N; j++) { | |
arr[i][j] = parseInt(document.querySelector("#queens-grid").children[i * N + j].classList[1].split("-")[2]) | |
} | |
} | |
function isSafe(board, row, col) { | |
// Check same column | |
for (let i = 0; i < row; i++) { | |
if (board[i][col]) { | |
return false; | |
} | |
} | |
const to_check = [ | |
[-1, -1], | |
[-1, 1], | |
[1, -1], | |
[1, 1] | |
] | |
for (let index = 0; index < to_check.length; index++) { | |
var x = to_check[index] | |
if (row + x[0] >= 0 && row + x[0] < N && col + x[1] >= 0 && col + x[1] < N && board[row + x[0]][col + x[1]] == 1) | |
return false; | |
} | |
return true; | |
} | |
function solveNQueens(n) { | |
const board = Array.from({ | |
length: n | |
}, () => Array(n).fill(0)); | |
const solutions = []; | |
function backtrack(row) { | |
if (row === n) { | |
// const solution = board.map((row) => row.map((x) => x ? 'Q' : '.').join('')); | |
const solution = [] | |
for (let i = 0; i < N; i++) { | |
for (let j = 0; j < N; j++) { | |
if (board[i][j] == 1) { | |
solution.push([i, j]) | |
} | |
} | |
} | |
solutions.push(solution); | |
return; | |
} | |
for (let col = 0; col < n; col++) { | |
if (isSafe(board, row, col)) { | |
board[row][col] = 1; | |
backtrack(row + 1); | |
board[row][col] = 0; // Backtrack | |
} | |
} | |
} | |
backtrack(0); | |
return solutions; | |
} | |
// Solve eight queen problem with custom rules | |
const eight_queen_sol = solveNQueens(N); | |
// console.log(eight_queen_sol); | |
// Check all possible solutions | |
for (let index = 0; index < eight_queen_sol.length; index++) { | |
var sol = eight_queen_sol[index] | |
var color_set = new Set() | |
for (let k = 0; k < sol.length; k++) { | |
color_set.add(arr[sol[k][0]][sol[k][1]]) | |
} | |
// console.log(color_set) | |
if (color_set.size == N) { | |
console.log(sol) | |
for (let index = 0; index < sol.length; index++) { | |
document.querySelector("#queens-grid").children[sol[index][0] * N + sol[index][1]].style.backgroundColor = "red" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment