ealione
ealione

Reputation: 1636

Why does this code for solving the n-queens puzzle does not work in javascript

For fun I decided to port the code that can be found on this plunkr from Matlab to Javascript.

     var propagate = function(depth, board, counter) {
      console.log("Current state >> depth:", depth, " board: ", board, " counter: ", counter);

      var validSolution = checkSolution(board);
      if ((depth == board.length + 1) && (validSolution)) {
        counter = counter + 1;
        console.log("Found solution [", counter, "] ", board);
      };

      if (depth <= board.length) {
        for (var i = 1; i <= board.length; i++) {
          if (!(board.indexOf(i) > -1)) {
            board[depth-1] = i;
            propagate(depth + 1, board, counter);
          };
        };
      };
    };

After reaching the final depth level though, I would expect it to continue where it left with the previous level. Instead it just stops.

Why is that?

Upvotes: 0

Views: 43

Answers (1)

Guffa
Guffa

Reputation: 700512

When you send the array as a parameter you won't get a new copy of the array, it's still the same array object. That means that the board won't change back when you return.

You can store the previous value of the item that you change, so that you can change the board back after the call:

if (!(board.indexOf(i) > -1)) {
  var prev = board[depth-1];
  board[depth-1] = i;
  propagate(depth + 1, board, counter);
  board[depth-1] = prev;
}

Upvotes: 2

Related Questions