So I'm making a unique sudoku puzzle generator and while creating the uniqueness, I am using a trial and error script with Math.floor(Math.Random()*X)
to get a random tile out of the 81 tiles to remove the number to the solution. I made it so that after removing X amount of tiles with numbers, it tries to solve it by checking all the possibilities. If it can't, then that means that there's multiple/no solution(s) and that it needs to generate a different puzzle whilst still using the same solution. It can manage to create a unique puzzle, but at some rare occasions it won't and will create a stack overflow since it's calling itself too many times.
I basically want a way to bypass the stack overflow.
I have looked up many solutions online, but none gave the result I want. The closest that I've gotten it to work the way I want was with a recursive async try{}catch(){}finally{}
function but I couldn't get it to stop when it actually found a solution or to print out the error whenever the stack overflow occurred.
async function fCreatePuzzle(solution) {
let refere = []
puzzleTries++
for (let i = 0; i <= 25 + difficulty - 1; i++) {
refere[i] = getRandomLetterAndNumber(refere)
}
for (let i = 0; i <= refere.length - 1; i++) {
containddd[refere[i]].Value = null
}
if (fTestSolve(solution) == false) {
for (key in containddd) {
fChangeSudokuValAdmin(key, containddd[key].Value)
}
} else {
if (puzzleTries >= 5500) {
LoadModalText.innerText = "Could not load puzzle with " + difficulty.toString() + " as the difficulty."
console.log("after " + puzzleTries + " attempts, we could not make a puzzle with " + difficulty.toString() + " as the difficulty. ")
difficulty = difficulty >= 0 && difficulty - 2 >= 0 && difficulty - 2 || 0
console.log("Lowering difficulty to " + (difficulty).toString() + " to try to create a 1 solution puzzle")
setTimeout(function(){LoadModalText.innerText = "Lowering difficulty to " + (difficulty).toString() + " to prevent overflow errors."},2000)
puzzleTries = 0
setTimeout(function(){LoadModalText.innerText = "Loading Puzzle..."},1750)
}
resetTest(solution)
fCreatePuzzle(solution)
}
return puzzleTries
}
function InitialiseGame() {
loadingModal.show();
Spinner.classList.add("spinner-border","spinner-border-sm")
LoadModalText.innerText = "Generating Sudoku Solution..."
setTimeout(function(){
Stime = new Date()
True_Solution = setupSudokuSolution()
LoadModalText.innerText = "Generating Sudoku Puzzle..."
async function run(){
try {
return await fCreatePuzzle(True_Solution)
} catch (e) {
console.log(e)
} finally {
run()
}
}
let what = run()
number_Chosen = null
LoadModalText.innerText = "Puzzle Generated Successfully!"
Spinner.classList.remove("spinner-border","spinner-border-sm")
setTimeout(function(){loadingModal.hide()},2000)
},200)
}