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 . . . 
. . . . . . . 
    . . .     
    . . .
4
  • also check this Commented Nov 12, 2019 at 8: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. Commented Nov 12, 2019 at 8: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. Commented Nov 12, 2019 at 8: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) Commented Nov 12, 2019 at 9:14

0

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.