0

I am trying to understand why my array updates its values before I want to apply changes to it with the function createRandomGrid. When I print the array before and after the modification, it prints the same result.

Can someone please explain me how this occurs?

let sudokuGrid = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],

  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],

  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0]
];

console.log(sudokuGrid)
createRandomGrid(sudokuGrid);
console.log(sudokuGrid)

function createRandomGrid(board) {
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      if (board[i][j] === 0) {
        for (let k = 1; k <= 9; k++) {
          let num = Math.floor(Math.random() * 9) + 1;
          if (isValidNode(i, j, num, board)) {
            board[i][j] = num;
            if (createRandomGrid(board)) return true;
            board[i][j] = 0;
          }
        }
        return false;
      }
    }
  }
  return true;
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
makekelly
  • 1
  • 2
  • 1
    You need to add to your question the code of the function createRandomGrid – ManuelMB Jan 17 '23 at 16:56
  • 1
    Probably due to the lazy evaluation of console logged objects in the browser - https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects – Brian Thompson Jan 17 '23 at 17:04
  • Hey, thanks for your answers. I added the function to the snippet. – makekelly Jan 17 '23 at 19:50
  • Probably because it doesn't – Kevin B Jan 17 '23 at 19:52
  • Please keep clicking "Run code snippet" until it demonstrates the error you believe it to be. Currently it is just throwing at error about the missing definition of the `isValidNode` function. Please do this yourself; you shouldn't need readers to tell you when your posted code demonstrates the error you are talking about. – Heretic Monkey Jan 17 '23 at 19:55
  • The function shall find a random solution for the empty grid. But it logs the random grid twice to the console. – makekelly Jan 17 '23 at 19:56
  • technically, it logs the grid without the values to the console. Then, when you expand it, you get the value of the grid at the point in time in which you expanded it, which is *after* it was changed. See brian thompson's link. – Kevin B Jan 17 '23 at 19:57
  • By the way, one of the principle tenets of React is immutability of data. You are mutating the data in `createRandomGrid`, thus violating that tenet. Instead, create a new copy of the array, with the changed data. One easy way to do that is via the `map` function. – Heretic Monkey Jan 17 '23 at 19:59
  • Great, thanks for all your answers and advises. – makekelly Jan 17 '23 at 20:30

0 Answers0