Sudoku Algorithm Problem

Ive been pieceing this together for a while and i am solving my puzzle but i cant get the loop to break out after it is solved. i have a ‘return true’ statement where i think i need it but it kicks it out way too early. When i comment it out i can get it solved about halfway through the code but it keeps running. Not sure how i can get it to stop.

First function is a function to transform string to a 2d array.

2nd function is a validation function.

3rd is the solve.

const boardstring = '..9..5.1.85.4....2432......1...69.83.9.....6.62.71...9......1945....4.37.4.3..6..'


function transform(puzzleString){
  const N = 9
  let row = -1
  let col = 0
  const grid = [ [], [] , [] , [], [] ,[] ,[] ,[] ,[]  ];
  let mystring = puzzleString
   for(let i = 0; i < mystring.length; i++){
     if(i % 9 == 0){
       row++
     }
     grid[row][col] = mystring[i];
     col++
     if(col % 9 == 0){
       col = 0;
     }
   }
   return grid
  }


  function isValid (row, col, board, val){   
        let rowDiff = Math.floor(row / 3) * 3;
        let colDiff = Math.floor(col / 3) * 3;
        
        for(let i = 0; i < board.length; i++) {          
            if(board[row][i] === val) return false;          
            if(board[i][col] === val) return false;         
            if(board[rowDiff + Math.floor(i / 3)][colDiff + i % 3] === val) {       
                return false;
            }         
        }  
  return true; 
    }

  
function solve(board){ 
  console.log(board) 
  // start row at 0 
        for(let row = 0; row < board.length; row++){
          
  //   console.log('stage 1')            
  //   start col at 0   
          
              for(let col = 0; col < board[row].length; col++){  
                
  //   if a character is 0 move to next loop
                
                   if(board[row][col] == '.') {
                     
   //  console.log('stage 2')                
  //   change '.' to loop through 1-9 
                     
                        for(let i = 1; i <= 9; i++) {
                          
   //   console.log('stage 3')
   //   console.log(i + ' '+ row + ' ' + col)                     
  //    check if new character is valid
                          
                             if(isValid(row, col, board, String(i))) {              
                                  board[row][col] = String(i);
                               
  //     console.log('stage 4')                             
  //     if new character is valid, start new solve loop
                               
                             if(solve(board)) {
                               
         console.log('stage 5')
         
   //                       return true;
         
                                }
                               
  //  console.log('stage 6')
  // if solve fails, change character back to '.'
                               
                               board[row][col] = '.';
                          }
                          
   //  console.log('not valid')
                          
                    }
                     
 //   console.log('stage 7')
                     
                 return true;
                }
                
//    console.log('stage 8')
                
            } 
          
//    console.log('stage 9')
          
        }
  
// console.log('stage 10')
  
  return board.flat(1).join(); 
            }



console.log(solve(transform(boardstring)))

i switched to a different approach to back tracking. I am using an idea i found online and i got it to work on JS Bin while testing it. I can get it to transform a string to an array and then take that array and solve it.

The problem is that it wont solve it in my web app. I added logging call outs at different stages and it seems as soon as it passes my validation method it wont recall the solve method on itself. I just dont understand what is different in the web app vs all the IDEs i have tried it in and have it working.



  transform(puzzleString){
    const N = 9
    let row = -1
    let col = 0
    const grid = [ [], [] , [] , [], [] ,[] ,[] ,[] ,[]  ];
    let mystring = puzzleString
  
     for(let i = 0; i < mystring.length; i++){
       if(i % 9 == 0){
         row++
       }
         grid[row][col] = mystring[i];
         col++
         if(col % 9 == 0){
           col = 0;
         }
     }
   return  grid
  }



  solve(data) {
    console.log('start solving')
    function isValid(board, row, col, k) {
      for (let i = 0; i < 9; i++) {
        const m = 3 * Math.floor(row / 3) + Math.floor(i / 3);
        const n = 3 * Math.floor(col / 3) + i % 3;
        if (board[row][i] == k || board[i][col] == k || board[m][n] == k) {
          console.log('failed valid')
          return false;
        }
    }
      console.log('sucess valid')
    return true;
}

  for (let i = 0; i < 9; i++) {
    console.log(i)
    for (let j = 0; j < 9; j++) {
      console.log(j)
      if (data[i][j] == '.') {
        for (let k = 1; k <= 9; k++) {
          console.log(k)
          if (isValid(data, i, j, k)) {
            console.log('success 4')
            data[i][j] = `${k}`;
          if (solve(data)) {
            console.log('success 1')
           return data;
          } else {
            console.log('failed 3')
           data[i][j] = '.';
          }
         }
       }
        console.log('failed 2')
       return false;
     }
   }
 }
    console.log('success 2')
 return data;
}

my route

 app.route('/api/solve')
    .post((req, res) => {
    const puzzlestring = req.body.puzzle;
      console.log(puzzlestring)
      const retarray = solver.transform(puzzlestring)
      console.log(retarray);
      const solution = solver.solve(retarray)
      console.log(solution)
      res,json({solutiion: solution})
      
    });

i havent added a filter to test if the string has valid characters or not yet but that shouldnt matter until i start testing other strings. i am just using a test string that should work

looks like i need to burhs up on my javascript class syntax. In order for me to recall the solve method. I needed to make sure it was calling an instance of the class by using this.solve

I believe i am hitting all of the storys. I printed all of the inputs on the api/check routes, but i am still failing.

I dont know if i am printing the json wrong?

Can someone run this through the test to see if it passes for them?

sudoku replit

free code camp test site

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.