I have been making a sudoku solver in JavaScript. There is a very weird behaviour. Here is the code and context:
solveSudoku = ()=>{
let sectionsCopy_ =sectionsCopy
for(let sect =0; sect< 9; sect++){
for(let box =0; box <9; box++){
if(sectionsCopy[sect][box] === ''){
for(let num=1; num<=9;num++){
if(this.isPossible(sect,box,num)){
sectionsCopy[sect][box]=''+num
this.solveSudoku()
sectionsCopy[sect][box]=''
}
}
return
}
}
}
debugger
console.log(sectionsCopy)
}
This is inside a class
sectionsCopy is a global variable
sectionsCopy_ is just for debugging (to see the value of the global var easily)
isPossible() is a function that determines if num is valid in that place
sect is the index of the 3x3 square in Sudoku
box is the index of the unit box in Sudoku
The problem:
Consider this Sudoku:
When you click solve the sectionsCopy variable will store :
[
["2","6","" ,"4","7","" ,"5","8","1"],
["" ,"" ,"3","" ,"" ,"" ,"" ,"" ,"4"],
["" ,"1","5","" ,"" ,"8","7","6","3"],
["" ,"3","" ,"" ,"" ,"6","" ,"" ,"8"],
["4","8","9","" ,"" ,"2","3","1","" ],
["" ,"7","" ,"8","3","" ,"" ,"" ,"" ],
["6","9","" ,"3","" ,"" ,"" ,"1","" ],
["" ,"" ,"8","" ,"9","" ,"5","" ,"" ],
["" ,"" ,"7","2","" ,"" ,"" ,"9","6"]
]
When I run it without the debugger being on I get this result:
If I turn on the debugger, I see this:
Here is side by side, the results when I dont use debugger vs when I use debugger:
I was expecting behaviour under debugger to be the same without debugger (or else it will be useless like this case)
I tried console.log(sectionsCopy_)
but I know arrays are immutable so it didnt matter