There is a grid that is 10 by 10 filled with numbers. The user starts somewhere on the grid and they can either go up, down, left or right. The number they are currently on corresponds to how many spaces they will move either up, down, left or right. The goal is to get to an top left or or right corner or a bottom left or right corner.
I have a recursive method written but when I want to print the output of the pathway that is needed to be taken the output should look like, without quotes, "up, down, left, up, down".
My question is how to write this and not have an extra comma at the end of the string? My input always comes out "up, down, left, up, down," with the extra comma. I know it's because it my string printout i put the comma but how do I within a recursive method have an if - statement that will not add a comma to the last move.
my code is below:
public String findSolution() {
// Call recursive method from here and return the string
// representing the path.
return backtrack(5, 5, "");
}
/**
* Recursive backtracking method for finding a path from a starting point.
*
* @param row
* - row of starting point
* @param col
* - column of starting point
* @param pathSoFar
* - the current path so far.
* @return whether a path was found
*/
public String backtrack(int row, int col, String pathSoFar) {
booleanArray[row][col] = true;
if (winningCond(row,col) == true) {
return pathSoFar;
} else {
steps = map[row][col];
/**
* try up.
*/
if(offBoard(row - steps, col) == false
&& booleanArray[row - steps][col] != true) {
return pathSoFar = backtrack(row
- steps, col, pathSoFar + "up");
}
/**
* if that didn't work try right.
*/
else if(offBoard(row, col + steps) == false
&& booleanArray[row][col + steps] != true) {
return pathSoFar = backtrack(row, col + steps,
pathSoFar + "right");
}
/**
* if that didn't work try down.
*/
else if(offBoard(row + steps, col) == false
&& booleanArray[row + steps][col] != true) {
return pathSoFar = backtrack(row + steps, col,
pathSoFar + "down");
}
/**
* if that didn't work try left.
*/
else if(offBoard(row, col - steps) == false
&& booleanArray[row][col - steps] != true) {
return pathSoFar = backtrack(row, col - steps,
pathSoFar + "left");
} else {
return null;
}
}
}