0

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:

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:

weird behaviour

If I turn on the debugger, I see this:

debugger

Here is side by side, the results when I dont use debugger vs when I use debugger:

Comparison

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

  • See that blue/purple box with the [i].... hover over it. – epascarello Nov 09 '22 at 18:26
  • It says: "This value was evaluated upon expanding. it may have changed since then" What does that mean? – Mina Eskandar Nov 09 '22 at 18:30
  • Means the value there is not the same value as it was when you logged it. console lazy logs data. https://stackoverflow.com/questions/23392111/console-log-async-or-sync or https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects – epascarello Nov 09 '22 at 18:37

1 Answers1

0

Thanks to @epascarello note.

seems like console.log is outputting data while it's being changed.

The solution I did was

let solution = JSON.parse(JSON.stringify(sections))
console.log(solution)

instead of

console.log(sections)
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36