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)))