1

I just finished implementing a backtracking algorithm which successfully solves a sudoku board. However, I would like to add delay so that it will be easier to visualize. Im assuming I need to use setTimeout() or setInterval(). I already tried adding them at the very beginning of the function but that did not work. So my question is, how do I structure this program to add the delay?

This is my code:

function backtracker(){
  for(var i = 0; i < 9; i++){
    for(var j = 0; j < 9; j++){
      if(bd[i][j].value=="."){

        for(var n=1;n<10;n++){
          if(isValid(bd,i,j,n)){
            bd[i][j].value=n;

            if(backtracker(bd)){
              return true;
            }else{
              bd[i][j].value=".";

            }
          }
        }
        return false;
      }
    }
  }
  return true;
}




//Used to check if number 'c' is allowed at coordinates (x,y)
function isValid(board,x,y,c){
  let rowStart = Math.floor(x/3) * 3;
  let colStart = Math.floor(y/3) * 3;


  for(let i=0; i<9; i++){
      if(board[i][y].value == c || board[x][i].value == c){ 
        return false};
  }

  for(let i=0; i<3; i++){
      for(let j=0; j<3; j++){

          if(board[rowStart+i][colStart+j].value == c){

             return false;
          }
      }
  }

  return true;

}
  • 1
    You'll need to wrap either this function, or all code in this function in a setTimeout. Regardless, you'll need to have a look at using [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) so you can make code run asynchronously. – Yannick K Jun 03 '20 at 21:11

1 Answers1

0

I don't know a direct implementation of synchronous execution pausing like "sleep" function in other languages like c or python.

but you can benefit from modern javascript syntactic sugar (async/await).

try this trick :


function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function backtracker() {
    // this will stop execution two seconds
    await sleep(2000);
    //
    for (var i = 0; i < 9; i++) {
        for (var j = 0; j < 9; j++) {
            if (bd[i][j].value == ".") {

                for (var n = 1; n < 10; n++) {
                    if (isValid(bd, i, j, n)) {
                        bd[i][j].value = n;

                        if (backtracker(bd)) {
                            return true;
                        } else {
                            bd[i][j].value = ".";

                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}


  • Thank you for the suggestion, It works good up until the backtracking part, at that point it just stops filling the next cells. – Abhishek Yadav Jun 03 '20 at 21:53
  • In my answer, I just tried to solve the timing problem, and i don't thing that's may affect your logic, maybe its an implementation problem. – ayoub aguert Jun 03 '20 at 22:37