1

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

3

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.