Recursive Problem

Howdy! I’m trying to make a Sudoku Solver and I can’t seem to figure out this bug. I’ve got too many console.logs in here but you should be able see what’s happening. I use a recursive function to try all possible numbers but when it fails, I want it to backtrack through the stack, however when it backtracks it’s keeping the same indecies. Any idea what’s wrong? Thanks!

function solve() {
  for (jj = 0; jj < size; jj++) {
    for (ii = 0; ii < size; ii++) {
      if (grid[jj * size + ii].value == 0) {
        for (n = 1; n < size + 1; n++) {
          console.log('test (' + ii + ',' + jj + ') = ' + n)
          if (grid[jj * size + ii].possible(n)) {
            grid[jj * size + ii].value = n;
            console.log('(' + ii + '),(' + jj + ') set to ' +grid[jj * size + ii].value);
            redraw();
            solve();
            grid[jj * size + ii].value = 0;
            console.log('(' + ii + '),(' + jj + ') set to ' +grid[jj * size + ii].value);
            redraw();
          }
        }
        console.log('back track');
        return
      }
    }
  }
}

Console Log

test (2,0) = 1 

(2),(0) set to 1 

test (3,0) = 1 

test (3,0) = 2 

(3),(0) set to 2 

test (5,0) = 1 

test (5,0) = 2 

test (5,0) = 3 

test (5,0) = 4 

(5),(0) set to 4 

test (6,0) = 1 

test (6,0) = 2 

test (6,0) = 3 

test (6,0) = 4 

test (6,0) = 5 

test (6,0) = 6 

test (6,0) = 7 

test (6,0) = 8 

(6),(0) set to 8 

test (7,0) = 1 

test (7,0) = 2 

test (7,0) = 3 

test (7,0) = 4 

test (7,0) = 5 

test (7,0) = 6 

test (7,0) = 7 

test (7,0) = 8 

test (7,0) = 9 

(7),(0) set to 9 

test (8,0) = 1 

test (8,0) = 2 

test (8,0) = 3 

test (8,0) = 4 

test (8,0) = 5 

test (8,0) = 6 

test (8,0) = 7 

test (8,0) = 8 

test (8,0) = 9 

back track 

(8),(0) set to 0 

back track 

(8),(0) set to 0 

back track 

(8),(0) set to 0 

back track 

(8),(0) set to 0 

back track 

(8),(0) set to 0 

back track 

▶[Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell, Cell]
2 Likes

I don’t think that I have ever seen recursive function without a parameter. Actually I think it just cannot work. Parameters give function a state and recursion is based on that state.

I found a decent resource on recursion. It touches sudoku too: https://www.cs.utah.edu/~germain/PPS/Topics/recursion.html

2 Likes

Gotcha! I’ll have to review this thoroughly. My references was this video, which uses a recursive algorithm without a parameter:

1 Like