The issue I am currently having is my code is failing to solve different variations of a peg solitaire board. My test program tests 4 simple solvable boards. (1 move solutions) one move up, one move down, one move left, one move right. My code solves these with no problems along with testing an unsolvable board. The issue I am having is with solving more complicated problems such as a plus, a rhombus, and a standard board.
I'm not quite sure how to add the recursion to this problem. I have added it at the end of the solveHelp method calling setupMove again but that breaks the rest of my code. Not allowing the simple solutions to be solved correctly.
What would be the best way to apply the recursion for this problem?
public static boolean setupMove(
boolean[][] pegs, int startX, int startY, int jumpX, int jumpY, int endX, int endY) {
// Look at all of the pegs in the board
for (int x = 0; x < pegs.length; x++) {
for (int y = 0; y < pegs[x].length; y++) {
if (pegs[x][y]) {
startX = x;
startY = y;
if (startX <= 5 && pegs[startX][startY] == true
&& pegs[startX + 1][startY] == true && pegs[startX + 2][startY] == false) {
tryMove(pegs, startX, startY, startX + 1, startY, startX + 2, startY);
}
if (startX >= 2 && pegs[startX][startY] == true
&& pegs[startX - 1][startY] == true && pegs[startX - 2][startY] == false) {
tryMove(pegs, startX, startY, startX - 1, startY, startX - 2, startY);
}
if (startY <= 5 && pegs[startX][startY] == true
&& pegs[startX][startY + 1] == true && pegs[startX][startY + 2] == false) {
tryMove(pegs, startX, startY, startX, startY + 1, startX, startY + 2);
}
if (startY >= 2 && pegs[startX][startY] == true
&& pegs[startX][startY - 1] == true && pegs[startX][startY - 2] == false) {
tryMove(pegs, startX, startY, startX, startY - 1, startX, startY - 2);
}
}
}
}
if (win) {
return true;
} else {
solution = null;
return false;
}
}
public static void tryMove(
boolean[][] pegs, int startX, int startY, int jumpX, int jumpY, int endX, int endY) {
pegs[startX][startY] = false;
pegs[jumpX][jumpY] = false;
pegs[endX][endY] = true;
prevSolution = solution;
solution = solution + " " + startY + " " + startX + " " + endY + " " + endX;
solveHelp(pegs, startX, startY, jumpX, jumpY, endX, endY);
}
public static void solveHelp(
boolean[][] pegs, int startX, int startY, int jumpX, int jumpY, int endX, int endY) {
for (int x = 0; x < pegs.length; x++) {
for (int y = 0; y < pegs[x].length; y++) {
if (pegs[x][y]) {
pegCount++;
}
}
}
if (pegs[3][3] && pegCount == 1) {
// WE WIN!!!
win = true;
}
if ((!win && pegCount == 1) || (endX < 0 || endY < 0
|| endX >= pegs.length || endY >= pegs[endX].length
|| (endX < 2 && endY < 2) || (endX >= 5 && endY < 2)
|| (endX < 2 && endY >= 5) || (endX >= 5 && endY >= 5))) {
pegs[startX][startY] = true;
pegs[jumpX][jumpY] = true;
pegs[endX][endY] = false;
pegCount++;
solution = prevSolution;
}
pegCount = 0;
}