I want to generate a sudoku puzzle using nodejs and recursion.
The state of my program is as follows
I start with an array of 81 zeros.
Next, I fill the 1st, 4th, and last block with nine different numbers from 1-9 because I can generate these numbers without worrying about blocks, rows, or columns.
The next step is the part I am stuck on, which is solving the actual sudoku.
I have created a "getSudokuNumbers" function which returns all of the numbers in the block, row, and column for a given cell.
Then I check if there is a number in that cell that is a possible solution
However, when the program is run there is sometimes an issue where there is no valid solution.
Essentially, my program doesn't try every solution to the puzzle, which is what I need it to do...
You can check out my codesandbox here https://codesandbox.io/s/bold-ishizaka-cn6g3?file=/src/index.js
Below highlights the important parts of the program
sudokuArr = new Array(81).fill(0);
// fills the first, fourth, and last block with numbers from 1-9
fillGrid()
const solveGrid = () => {
// loop over every cell in the sudokuArr
for (let i = 0; i < sudokuArr.length; i++) {
// gets the index of the cell's block, row, and col
const { block, row, col } = getSudokuVars(i);
// gets the numbers in the current cell's row, column, and block
const blockNums = getNumbersInBlock(block),
rowNums = getNumbersInRow(row),
colNums = getNumbersInCol(col);
// all the numbers to try for every cell
const numsToTry = [1, 2, 3, 4, 5, 6, 7, 8, 9];
numsToTry.forEach((num) => {
// check that the number is a valid sudoku number
// however, this is where the problem arrises because sometimes the blockNums, colNums, and rowNums include every number from 1-9 and the program does not do anything.
// I believe this is where I need some sort of recursion/brute force algorithmn to
// try ever possible solution
if (
!blockNums.includes(num) &&
!rowNums.includes(num) &&
!colNums.includes(num)
)
return (sudokuArr[i] = num);
});
}
};