0

I am trying to solve a peg solitaire game using javascript. But when I try to do function recursive the error I get is

RangeError: Maximum call stack size exceeded.

Someone who has an idea about the problem. Please help

function findSolution() {

  if (numberOfPegs == 1 && myBoard[3][3] == "*") {
    console.log("Solution found")
    printBoard(myBoard)
    return true;
  } else {

    for (let i = 0; i < height; i++) {
      for (let k = 0; k < width; k++) {
        for (let dire = 0; dire < 4; dire++) {

          if (letsMove(i, k, directions[dire])) {
            numberOfPegs--;
            printBoard(myBoard)
          }

          //The error is here when I try to do function recursive
          if (findSolution()) {
            return true;
          }

          if (backStep(i, k, directions[dire])) {
            numberOfPegs++;
          }
        }
      }
    }

    return false;
  }
}

Input

    o o o     
    o o o     
o o o o o o o 
o o o . o o o 
o o o o o o o 
    o o o     
    o o o 

output

   . . .     
    . . .     
. . . . . . . 
. . . o . . . 
. . . . . . . 
    . . .     
    . . .
adiga
  • 34,372
  • 9
  • 61
  • 83
  • also check [this](https://stackoverflow.com/questions/26502457/understanding-recursion-in-javascript-and-alternative) – Reza Nov 12 '19 at 08:22
  • I believe since you are using global variables, every call to `findSolution()` will perform the exact same operations, if `numberOfPegs == 1 && myBoard[3][3] == "*"` and `letsMove(i, k, directions[dire])` are `false`. I.e. the algorithm doesn't make any progress at all and is stuck forever. Why are you calling `findSolution()` at all? I wouldn't be suprised if the approach is fundamentally flawed. – Felix Kling Nov 12 '19 at 08:25
  • Every time when function is call its add in `call stack` and `call stack` is in limited size.If your code is reached that size then you get this error.  This happen when your `recursive function` never end. – Sandip Patel Nov 12 '19 at 08:40
  • @FelixKling, By calling ffindSolution() if letsMove() function reduce the number of numsPegs to 1. If so the findSolution() has to return true. If i don't call the findSolution() . the algorithm will check only (both directions lead to no solution and it will return false) – Mudzanani Mushe Tshimangadzo Nov 12 '19 at 09:14

0 Answers0