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 . . .
. . . . . . .
. . .
. . .
findSolution()will perform the exact same operations, ifnumberOfPegs == 1 && myBoard[3][3] == "*"andletsMove(i, k, directions[dire])arefalse. I.e. the algorithm doesn't make any progress at all and is stuck forever. Why are you callingfindSolution()at all? I wouldn't be suprised if the approach is fundamentally flawed.call stackandcall stackis in limited size.If your code is reached that size then you get this error. This happen when yourrecursive functionnever end.