Here I have an async function in javascript that is used to fill up the sudoku board with numbers (basically its solution). I used a sleeper function between each number insertion so that the user can get a better feel of the recursion and backtracking algorithm, however after the fifteenth number gets inserted, the function stops by itself... What is going on here exactly ?
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];
}
}
}
}
CodePudding user response:
I think you forgot to await
the recursive call to solve
, so it will always return a promise, which it's truthy, and your function will terminate.