Sudoku Solver QA Project

Hey everyone,

I’ve been working on the Sudoku Solver QA project, and I think I’ve got it very close to working correctly. The problem I’m having is that when I solve the puzzle, my function will reach the correct solution but then instead of returning that solution it will continue running and remove all of the correct numbers, reverting back to the original puzzle string.

I’m not sure why it’s doing this, because it looks like it should stop running the function and return the completed solution when it is reached.

Here is my solve function:

solve(puzzleString, row, col) {
    let letter = {
      '0': 'A',
      '1': 'B',
      '2': 'C',
      '3': 'D',
      '4': 'E',
      '5': 'F',
      '6': 'G',
      '7': 'H',
      '8': 'I'
    }
    if (!puzzleString) {
      return { error: 'Required field missing' };
    }
    if (this.validate(puzzleString).error) {
      return this.validate(puzzleString);
    }
    let solutionString = [...puzzleString];

    if (col === 9) {
      col = 0;
      row++;
    }

    if (row === 9) {
      console.log('if (row === 9) : ' + solutionString.join(''));
      return { solution: solutionString.join('') };
    };

    let index = (row * 9) + col;
    if (solutionString[index] != '.'){
      return this.solve(solutionString.join(''), row, col + 1);
    }
    let coord = letter[row] + (col + 1);
    for (let i = 1; i < 10; i++) {
      if (!this.checkPlacement(solutionString.join(''), coord, i).conflict) {
        solutionString[index] = i;
        if (!this.solve(solutionString.join(''), row, col).error) {
          console.log(solutionString.join(''));
          return {solution: solutionString.join('')}; 
        }else{
          solutionString[index] = '.';
        }
      }
    }
    return { error: 'Puzzle cannot be solved'};
  }

Is anyone able to give me any pointers on this?

Thank you!

1 Like

I’ve looked at this, but I really need more information. This looks like one method of a class since you are calling this.validate() and this.checkPlacement(). I really need to see it run to be of assistance. If you can provide the whole class or a link to the project on repl.it or glitch, I may be able to help out if you still need assistance.

In general though, when a recursive algorithm does not stop when you want it to stop, it usually means the base case (or stopping case) is not working as intended.

Good luck.

Hey Jeremy,

Thank you for looking into this. I ended up re-writing this method and creating a nested array to handle the puzzle string, instead of converting it to a regular array. Once I did that, it worked as expected and returned the solution.

Here is a link to my completed project: https://repl.it/@murphy1188/sudoku-solver-project.

Thanks again!

1 Like

Hi Murphy, is there a way I can reach out to you, maybe on Twitter or linkedin? I’d very much like to. Thanks :blush:

I don’t have Twitter or Linkedin, but you can shoot me a message on here if you’d like.