How do you break out of recursion with no base case - java

So im working on this program that will recursively solve a maze that i get from a txt file. I put the maze into a 2d array. Here is an example of the most simple maze.
+-+-+-+
|S| |
+ + + +
| |E|
+-+-+-+
i know im probably not going about solving the maze in the best way but i think my way works i just need to know how to break out of my recursion loop. What im doing is checking if there is a boarder in the next place and if there is a '*' two places later if not then i move there and put down a marker. This got me to the end of the maze but it breaks after. I need a way to break out of the loop. I just started learning about recursion so i think this is the problem but im not exactly sure.
The wrong choice method will return me to the last place where there is a cell with an open boarder and a no '*' with in two places.
public static void solveMaze(int COL, int ROW){
//find first open cell and choose it
if(drawArray[COL][ROW+1] == ' ' && drawArray[COL][ROW+2] != '*'){
//if(drawArray[COL][ROW+2] == 'E')
drawArray[COL][ROW+2] = '*';
ROW+= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL+1][ROW] == ' ' && drawArray[COL+2][ROW] != '*'){
drawArray[COL+2][ROW] = '*';
COL+= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL][ROW-1] == ' ' && drawArray[COL][ROW-2] != '*'){
drawArray[COL][ROW-2] = '*';
ROW-= 2;
solveMaze(COL,ROW);
}
else if(drawArray[COL-1][ROW] == ' ' && drawArray[COL-2][ROW] != '*'){
drawArray[COL-2][ROW] = '*';
COL+= 2;
solveMaze(COL,ROW);
}
else
wrongChoice(COL,ROW);
}

One can provide a partial result (initially empty) as parameter. And one can return a result.
Another parameter for recursion often is the set of possible candidates.
For instance something like:
public static void solveMaze(int COL, int ROW, Path pathTaken) {
Path pathTaken = new Path();
if (solveMazeRecursively(START_COL, START_ROW, pathTaken)) {
...
}
}
private static boolean solveMazeRecursively(int COL, int ROW, Path pathTaken) {
if (drawArray[COL][ROW+1] == 'E') {
System.out.println(pathTaken);
return true;
}
// The real work...
if (drawArray[COL][ROW+1] == ' ' && drawArray[COL][ROW+2] != '*'){
drawArray[COL][ROW+2] = '*';
ROW += 2;
takenPath.add(COL, ROW+2);
if (solveMazeRecursively(COL,ROW, takenPath)) {
return true;
}
takenPath.remove(COL, ROW+2);
}
Recursion implies being lazy checking first whether nothing has to be done (solution present, or impossible to continue), and otherwise delegating to new function instances.

Related

How can I tell my code that it has a "Flush"?

I'm suppose to create a code that recognizes if my hand has the same card faces
public static boolean sameFace(String hand) {
hand = "s9s7s2sQsK";
char f = hand.charAt(0);
if( hand.charAt(0)==hand.charAt(2) && hand.charAt(0)==hand.charAt(4)
&& hand.charAt(0)==hand.charAt(6) && hand.charAt(0)==hand.charAt(8));
return (hand.charAt(0) == hand.charAt(2) && hand.charAt(0) == hand.charAt(4)
&& hand.charAt(0) == hand.charAt(6) && hand.charAt(0) == hand.charAt(8));
sameface = hand;
if (hand==true;)
return (hand==true;) ;
}
As can be seen above, if all positions are the same characters, it comes true(False, if even one isn't the same.) How can I then use the result of that "return" to let my program recognize it has the same faces or not? If that is even possible.
From what i know, based on my code, it's saying "Yes, positions x=y=z are the same" how can I then tell it "Since they are the same, they have the same card faces."
I tried to put this at the end
sameface = hand;
if (hand==true;)
return (hand==true;) ;
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
You do that simply by returning the result of the expression:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
return f == hand.charAt(2) &&
f == hand.charAt(4) &&
f == hand.charAt(6) &&
f == hand.charAt(8);
}
Or if you want to be friendly to a different number of cards, use a loop:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
for (int i = 2, len = hand.length(); i < len; i += 2) {
if (f != hand.charAt(i)) {
// Not a match
return false;
}
}
// All matched
return true;
}

odd if statement behavior in java

I'm having a weird issue with if-else statements in java. Below is a recursive method that attempts to find the end of a maze called getPathThroughMaze.
private static String getPathThroughMaze(char[][] maze, Set<Point> visited, Point currentPoint) {
int currentX = currentPoint.x;
int currentY = currentPoint.y;
visited.add(currentPoint);
//end case. append '!' so we know which path leads to the end of the maze
if (currentX == (xLength - 2) && currentY == (yLength - 1)) {
return "!";
}
char left = maze[currentY][currentX - 1];
char right = maze[currentY][currentX + 1];
char up = maze[currentY - 1][currentX];
char down = maze[currentY + 1][currentX];
char current = maze[currentY][currentX];
/* If valid, visit all non-visited adjacent squares.
Only odd numbered columns will be traversed
since even numbered columns represent vertical wall
columns
*/
if (right == '_' || right == ' ') {
Point nextPoint = new Point(currentX + 2, currentY);
if (!visited.contains(nextPoint)) {
String path = "E" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
}else {
//do nothing.
}
} else if (up == ' ') {
Point nextPoint = new Point(currentX, currentY - 1);
if (!visited.contains(nextPoint)) {
String path = "N" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else if ( current == ' ' && (down == '_' || down == ' ')) {
Point nextPoint = new Point(currentX, currentY + 1);
if (!visited.contains(nextPoint)) {
String path = "S" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else if (left == '_' || left == ' ') {
Point nextPoint = new Point(currentX - 2, currentY);
if (!visited.contains(nextPoint)) {
String path = "W" + getPathThroughMaze(maze, visited, nextPoint);
if (path.endsWith("!")) {
return path;
} else {
//do nothing.
}
} else {
//do nothing.
}
} else {
return "";
}
//otherwise...
return "";
}
At the point in the recursion where I run into a problem the variables are:
currentX = 3
currentY = 2
right = '|'
left = '|'
up = ' '
down = '_'
current = ' '
visited contains points (1,1), (3,1), (3,2)
In the first else if statement:
else if (up == ' ')
a new point (3,1) is created which IS already contained in the visited set. What I expect to happen is that
if(!visited.contains(nextPoint))
will evaluate to false and that I will (maybe after a few step over clicks in the debugger) arrive at
else if ( current == ' ' && (down == '_' || down == ' '))
where I can then check that condition (which I expect to be true) and continue traversing the maze. What actually happens is when I click step over on
if(!visited.contains(nextPoint))
the debugger (in both elcipse and intellij) moves all the way to the very last return statement of my method and it wants to return "". I don't understand why all my other if else statements are being skipped. Can anyone enlighten me as to why that might be the case? Please let me know if my explanation isn't clear enough.
If/else statements are exclusive, so you will not arrive to else if ( current == ' ' && (down == '_' || down == ' ')) as you have already entered the else if (up == ' ') branch. As if(!visited.contains(nextPoint)) in the inner if is false, the program goes into its else part with //do nothing comment and does nothing (actually, you don't need to and shouldn't write an empty else statement. At least add a log statement to it to make it easier to debug). Then it exits the if/else block and goes to return.
If you want your code to check every branch of if/else on every method call, just replace it with a number of simple if statements.
I.e. instead of:
if (condition1){
} else if (condition2){
} else if (condition3){
}
write
if (condition1){
}
if (condition2){
}
if (condition3){
}

How to compare three boolean values

Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!
if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)
How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}
Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}
Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement
try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}

java - recursive program for judging the validity of expression syntax (beginner)

I'm just learning java, and I have an assignment where I have to write a program that checks the validity of expressions about sets. Valid expressions are capital letters, an expression with a tilde in front, and can be combined using + and x as well as with parentheses. I've written a program that almost works, but I can't figure out how to get the binary operators to work with the parentheses.
It may also be that I have approached the problem in the wrong way (trying to validate from left to right, ignoring everything to the left once it's been validated). I can use any help I can get about writing recursive programs for this sort of problem; that is, if you have any pointers for a better way of approaching the problem, that would be incredibly helpful.
For reference, here is the code that I have:
public static boolean check(String expr) {
char spot;
int close=0;
expr = expr.trim();
//base case
if (expr.length() == 1 && expr.charAt(0)>= 'A' && expr.charAt(0) <= 'Z')
return true;
if (expr.charAt(0) == '~') {
if (expr.charAt(1) == 'x' || expr.charAt(1) == '+' || expr.charAt(1) == ')')
return false;
return check(expr.substring(1));
}
if (expr.indexOf('x') > 0 && expr.indexOf('x') > expr.indexOf(')')) {
int x = expr.indexOf('x');
if (check(expr.substring(0, x)) && check(expr.substring(x)))
return true;
}
if (expr.indexOf('+') > 0 && expr.indexOf('+') > expr.indexOf(')')) {
int plus = expr.indexOf('+');
if (check(expr.substring(0, plus)) && check(expr.substring(plus+1)))
return true;
}
if (expr.charAt(0) == '(') {
close = findEnd(expr.substring(1));
if (close < 0)
return false;
if (check(expr.substring(1,close)) && check(expr.substring(close+1)))
return true;
}
return false;
}
I'm not sure why your code is that complex. Recursion for this is pretty simple overall; here's what I'd do:
public static boolean check(String str) {
if(str.equals("")) return true;
if(str.charAt(0).isAlphaNumeric() || str.charAt(0) == '(' || str.charAt(0) == ')') return check(str.substring(1));
return false;
}
Your edge cases are if the string is empty; if this is the case, then the string is valid. If the character doesn't match what you're looking for, return false. Otherwise, check the next character.

Java array - Adjacent cards

I'm trying to create a program that arranges 6 cards on a grid in a specific way so that no card is adjacent to other cards of the same type (the types being king, queen and jack). The grid is 4x4 but I can only place cards inside the following pattern:
[ ][ ][x][ ]
[x][x][x][ ]
[ ][x][x][x]
[ ][ ][x][ ]
Now, my main problem is when my method tries to check the adjacent cells for card types. When it starts at 0,0 it tries to check [row-1][column] which obviously won't work since that translates to -1,0. The problem is, I have no idea how implement this properly.
I apologise if this question has been asked before, as I wasn't sure what to search for exactly (or how to properly name this problem).
private boolean bordersCard(int row, int column, char cardChar)
{
Candidate center = board[row][column];
Candidate top;
Candidate bottom;
Candidate left;
Candidate right;
if (board[row-1][column] != null){
top = board[row+1][column];
}
else
{
top = new Candidate('?', 0);
}
if (board[row+1][column] != null){
bottom = board[row+1][column];
}
else
{
bottom = new Candidate('?', 0);
}
if (board[row][column-1] != null){
left = board[row][column-1];
}
else
{
left = new Candidate('?', 0);
}
if (board[row][column+1] != null){
right = board[row][column+1];
}
else
{
right = new Candidate('?', 0);
}
if ((center.getCardChar() == top.getCardChar()) || (center.getCardChar() == bottom.getCardChar()) ||
(center.getCardChar() == left.getCardChar()) || (center.getCardChar() == right.getCardChar())){
return false;
}
return true;
}
You have to add if fences to prevent the invalid checks:
if (row > 0 && board[row-1][column] != null){
top = board[row+1][column];
}
If any of the indexes are out of bounds assign them to NULL. In Candidate create a method isSameType(Candidate other);
isSameType(Candidate other)
{
if(other == null)
return false;
else
retrun getCardChar() == other.getCardChar();
}
change your if to:
if(center.isSameType(top) || center.isSameType(bottom) || ...)
{
return false;
}
As you have determined, checking [-1][0] doesn't work. But you don't need to check that non-existent slot. Just make sure you don't run off the beginning or the end of the array. Also, make sure you are performing the same math operation inside your if as in your condition:
if ((row - 1) >= 0 && (row - 1) < board.length && board[row-1][column] != null){
top = board[row-1][column]; // Use -1 to match condition.
}

Categories