0

I'm new here so sorry if dublicate.

I'm trying to write a sudoku solver using backtracking method to make it pass all data dynamically into the document with its each recursion. When I tried to use setInterval() or setTimeout() it doesn't work the way I want it to work. What I need should be similar to this

Here's the code:

function backtrack(position) {
    if (position === 81) { 
        return true;
    }
    if (sudokuArray[position] > 0) {
        backtrack(position + 1);
    } else {
        for (var x = 1; x <= 9; x++) {
            if (isValid(x, parseInt(position / 9), position % 9) === true) { 
                sudokuArray[position] = x;
                //some code that invokes putSudokuArrayBack function with a small delay 
                //everytime backtrack function is invoked
                if (backtrack(position + 1) === true) { 
                    return true; 
                }
            }
        }
        sudokuArray[position] = 0; 
        return false; 
    }

}

function putSudokuArrayBack() {
    for (var i = 0; i <= 81; i++) {
        var indexString = '#val-' + parseInt(i / 9) + '-' + i % 9;
        $(indexString).val(sudokuArray[i]);
    }
}

Any ideas(if it's even possible)? Thanks in advance!

Gaz
  • 43
  • 4
  • You'll need to remove the loop and code it completely recursive. Then you can easily use `setTimeout` – Bergi Mar 15 '15 at 17:08
  • @Bergi You mean like this http://pastebin.com/F6bBs5K0 ? I've tried it but it only makes a delay once and then returns whole solution to sudoku. But I need to see how program selects values into cells step by step. – Gaz Mar 15 '15 at 18:44
  • No, a) you need to get rid of the `for` loop b) it's the `backtrack(position + 1)` call that needs to go into the `setTimeout` – Bergi Mar 15 '15 at 19:56
  • You might want to have a look at [this question](http://stackoverflow.com/q/11665484/1048572) which asks for something similar (albeit on a different algorithm) – Bergi Mar 15 '15 at 19:57
  • So, [I did what you've said](http://pastebin.com/duF1BpUc) and it actually updates data and sets a delay. However, it doesn't backtracks anymore. Apparently, it stucks when the function cannot find valid number. What am I doing wrong? – Gaz Mar 15 '15 at 21:56

0 Answers0