Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized between each number insertion. However, an issue arises where the function abruptly stops after inserting the fifteenth number. What exactly could be causing this unexpected halt?
var finalInd;
function sleep() {
console.log("happy")
return new Promise(resolve => setTimeout(resolve, 100));
}
async function solve () {
allowed = false;
var empty = findEmptySpace();
if(!empty) {
return true;
}
for(let i=1; i<10; i++) {
if(checkDuplicates(board, i, empty)) {
board[empty[0]][empty[1]] = i;
finalInd = (empty[0]*9) + empty[1];
await sleep()
funcId("board").children[finalInd].innerHTML = i;
if(solve(board)) {
return true;
}
board[empty[0]][empty[1]] = 0;
funcId("board").children[finalInd].innerHTML = 0;
}
}
funcId("board").children[0].innerHTML = board[0][0];
return false;
}
function checkDuplicates (board, num, empty) {
for(let i=0; i<9; i++) {
if(board[empty[0]][i] == num && empty[1] != i) {
return false;
}
}
for(let i=0; i<9; i++) {
if(board[i][empty[1]] == num && empty[0] != i) {
return false;
}
}
var x = Math.floor(empty[1]/3);
var y = Math.floor(empty[0]/3);
for(let i=(y*3); i<(y*3)+3; i++) {
for(let j=(x*3); j<(x*3)+3; j++) {
if(board[i][j] == num && i != empty[0] && j != empty[1]) {
return false;
}
}
}
return true;
}
function findEmptySpace () {
for(let i=0; i<9; i++) {
for(let j=0; j<9; j++) {
if(board[i][j] == 0) {
return [i, j];
}
}
}
}