Trying to come up with solution using recursion - java

I know there are multiple ways to find out if a word is palindromic, like using the reverse function of StringBuilder or even the reverse function of Collections, but in an attempt to learn recursion, I wrote it this way. I even had it working iteratively.
I kind of added return true in my embedded else statement, but I'm really not sure what to do, because when I run this in debug mode, it returns false, then invokes checkPalindrome again, which I don't understand why, because it should return and terminate, no? I would really appreciate an explanation of what I'm doing wrong and how to get it working this way.
public static boolean checkPalindrome(Deque deq) {
if(deq.pollFirst() != deq.pollLast()) {
return false;
} else {
if(deq.size() == 1 || deq.size() == 0) {
return true;
} else {
checkPalindrome(deq);
return true // TODO ?? figure out What to put here ??
}
}
}

It's that you are not returning anything when you call yourself. The inner else statement should read this:
else {
return checkPalindrome(deq);
}
You have a followup question in the comments below that leads me to want to explain how recursive methods work, but in essence, they all follow the following pseudo-code:
public boolean someMethod(T[] someArrayOrList) {
// return true -OR-
// return false -OR-
// call yourself and return whatever that call returns
}
No matter what, when you call the method it will return SOMETHING... Either it will return something itself, or it will return whatever some other call of itself will return. In a way it is AND'ing all the responses, but in reality TRUE is only generated once.

Related

Java boolean "Unexpected return value"

I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement.
My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!
public boolean isStateNameClaimed(String NameOfState)
{
States.forEach((IdentifierOfState, ValueOfState) ->
{
if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
else {return false;}
});
return false;
}
The problem is that you are attempting to return the results in the wrong place. The {return true;} and {return true;} are in a lambda, so they are attempting to return a result for the lambda. But the inferred type signature for that lambda doesn't allow any values to be returned.
If your intention is that those return statements should be returning a result from isStateNameClaimed, then the better solution is to just use a for loop to iterate the elements of States.
It doesn't help things that your Java code contains a number of egregious Java style violations. You should NOT start the name of a variable with an upper-case letter. It will confuse ... and then annoy ... other people reading your code.
You may say: "Nah, I don't need to follow the rules, 'cos nobody else will be reading my code". But you are asking >>us<< to read your code.
I'm new to Java ...
... so NOW is the time to learn to do it correctly. Java style matters to people reading your code.
This is how I would write it in classic Java:
public boolean isStateNameClaimed(String name) {
for (State v: states.values()) {
if (v.getNameOfState().equalsIgnoreCase(name)) {
return true;
} else {
return false;
}
}
return false;
}
Or using streams:
public boolean isStateNameClaimed(String name) {
return states.values().stream().anyMatch(
(v) -> v.getNameOfState().equalsIgnoreCase(name));
}
Actually ... I just noticed that those two solutions are not equivalent. And based on your description of what you are trying to do, it probably means that the first one and your original attempt are algorithmically incorrect.
forEach will invoke a given callable function for every element. We can't have return value to that function.
Try using "filter" or assign result to local variable.
Return from lambda forEach() in java

Stop a chain of methods without returning booleans

I have not doubt that there is a solution posted for this, but I can't find the search term retrieve it, so if it does exist please point me to the duplicate and mark this as such.
I have a chain of methods performing various validation checks on a button click event, I display a message if the validation has failed, currently my solution is to then pass back a boolean so that if the method failed the remaining methods will not run.
I don't like this, when I have several methods all passing back booleans my code starts to smell.
is there a better solution to this? (I'd don't want to use a instance variable)
Example of the code as it currently stands:
private void SUBMIT_BUTTON_CLICK(){
if(validate()){
//Do Stuff
}
}
private boolean validate(){
return checkOne() && checkTow() && checkThree() && checkFour();
}
private boolean checkOne(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkTow(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkThree(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
private boolean checkFour(){
if (someCheckFails) {
print(warning);
return false;
} else {
return true;
}
}
Convenionally you would use exceptions:
void check1(Foo value) {
if(some test on value) {
throw new ValidationException(...);
}
}
try {
check1(value);
check2(value);
} catch (ValidationException e) {
// deal with validation failure
}
A bonus here is that the exception can carry information about the failure. Your boolean false just says "it failed", with no explanation.
Another bonus, of course, is that you're free to pass the exception higher up the call stack, where some other code can deal with it.
Some people worry about the cost of building exceptions (or more accurately, collecting that stack trace contained within). I'd advise not worrying about it unless you get performance problems and profiling points the finger at exceptions.
There are alternatives though. For example your validation could return Optional<ValidationError>:
Optional<ValidationError> check1(Foo value) {
if(some test on value) {
return Optional.of(new ValidationError(...));
} else {
return Optional.empty();
}
}
Then...
Optional<ValidationError> validationResult =
check1(value)
.orElseGet( () -> check2(value))
.orElseGet( () -> check3(value));
You could, of course, loop through a list of validators, rather than hard-code like this.
Some of the functional programming libraries (e.g. vavr) include an Either class, which can be used in a similar way, where instead of being either an error or empty(), it's an error or a success value.
Or you could stick with methods returning boolean, but use them as Predicates:
List<Predicate<Foo>> checks = Arrays.asList(
f -> check1(f),
f -> check2(f),
f -> check3(f)
);
(Or the equivalent with method references e.g. this::check1)
checks.stream().allMatch(check -> check.test(value));
As you can see, there are tons of possibilities. But think about whether you're over-complicating. There's mostly nothing inherently wrong with the simple approach you already have -- although it is better, and more testable, to return a failure reason, rather than print it as a side-effect.
Chaining like you are currently doing is generally the best solution. It is easy to understand, efficient and (relatively) concise.
A couple of other ideas would be:
build an array of predicates and then iterate and call them, or
use exceptions and exception handling
but both of these have performance implications, and they will only give "cleaner" code if you have a vast number of predicates to evaluate.
Sometimes an inelegant solution is more elegant than looking for a clever solution.
Consider this: if I use exceptions, I can rewrite the validate() method
private boolean validate(){
return checkOne() && checkTow() && checkThree() && checkFour();
}
as
private void validate() throws ValidationException {
checkOne(); checkTow(); checkThree(); checkFour();
}
But how much have I actually gained here? It is still two lines of code. And if I were to follow Java's style rules it would be:
private void validate() throws ValidationException {
checkOne();
checkTow();
checkThree();
checkFour();
}
which is more lines than we started with. And we haven't considered the predicates themselves or the code that handles the validation exception.
Based on my comment: you're probably after exceptions.
Example (pseudo code):
void checkOne() {
if( check_fails ) {
throw new CheckOneException();
}
}
void checkTwo() {
if( check_fails ) {
throw new CheckTwoException();
}
}
void validate() {
checkOne();
checkTwo();
}
void SUBMIT_BUTTON_CLICK() {
try {
validate();
//Do Stuff
} catch( CheckOneException | CheckTwoException ) {
//handle the exceptions
}
}
Note that you might have to either declare the exceptions to be thrown or make them runtime exceptions.
Additionally you might want to use multiple catch-blocks if the handling depends on the type of exception. Alternatively you could also throw the same type of exception if that fits your needs.

Return keywords for a boolean statement

I am writing an incredibly primitive blackjack game for a high school programming class and I am playing with writing a boolean as such:
public boolean DealerTracker()
{
if(a==11 || a==12|| a==13)
{
a = 10;
}
dealerHandValue = a + dealerHandValue;
if(dealerHandValue>21)
{
DealerHand.setText("The House went bust!! Everybody wins!!");
return true;
}
else if(dealerHandValue<21)
{
return null;
}
else if(dealerHandValue==21)
{
return false;
}
}
I keep getting an error saying that return null (I couldn't manage to get the fancy blockquote to work) is invalid. However, for this boolean to work I really need three return statements. So my question is this: Is there a way to make null work, or is there something I can put in its place that is still usuable, or am I just being stupid here.
Please note that I do not really need this boolean, so if you think that there is no solution, just advise deletion of the boolean.
Primitives booleans can only return values true or false. You need to return the Object wrapper type for boolean
public Boolean dealerTracker() {
...
boolean primitives cannot be null. You basically have two options I can see:
Have your function return a Boolean (note the capital 'B'). Boolean is an object, rather than a primitive, and so can be null.
A better solution would be to define an enum. That helps you preserve the semantic meaning of the return value, which will make your code more readable and easier to maintain.
If you don't really need the boolean, make the return type void and remove all return statements. If you do need boolean AND null, change the return type to Boolean, which will return a boolean wrapped in an object that can actually be null. The method that calls this method can then receive a true, false, or null, since null actually represents something too (although I'm not sure in this case it represents anything meaningful).

Why doesn't this if-statement short circuit?

I'm currently fixing a bug in someone else's Java code, but I cannot explain the bug. The code in question is the following if-statement:
if (locked && DEBUG_ENABLED
&& owner != null
&& (owner.equals(playerName) || subowner.equals(playerName))
&& handleCommand(playerName, message)) {
....
} else {
....
}
In which DEBUG_ENABLED is initialized as private static boolean DEBUG_ENABLED = false; and handleCommand functions like this:
public boolean handleCommand(String name, String msg) {
if(msg.equals("Command1")) {
....
} else if(msg.equals("Command2")) {
....
} ....
} else { // No matching command
return false;
}
return true;
}
What puzzles me is that even though DEBUG_ENABLED is set to false, the code still calls and executes the handleCommand function. I always thought this wasn't supposed to happen due to short circuiting.
The if-statement itself in total is still evaluated as false, since only the code inside the else-block in the first snippet is executed.
So, how come this if-statement is behaving like this? Is it failing to short-circuit, or do I misunderstand the principle, or is there something completely different wrong with this part of code? (Besides the missing null check for subowner that is, which is done outside of this part.)
It is not possible that the && operator fails to short-circuit. Were you using & perhaps? If not it means you have made some false assumptions that previous conditions before the last one were false.

Java Stack Comparison

I'm wondering how to accomplish this:
Compare two Stack objects
Do this recursively
After the method that
does this is complete, the Stacks remain as they were to begin with
(i.e. same order, same items).
Only the push, pop and isEmpty methods for Stack is available.
I'm looking more for theoretical help than coding help, but any insight would be appreciated.
Two stacks are identical if their top level elements are identical, and the remaining stacks are identical (namely, the recursive condition).
Now, think what to do just before returning from the method call, in order to leave the stacks the same way they where given at the invocation time.
---EDIT---
The working Java code (derived from Markus A. solution, but with an interesting use of "finally" and with generics):
static <T> boolean compareStacks(Stack<T> a, Stack<T> b) {
if (a.isEmpty() != b.isEmpty()) return false;
if (a.isEmpty() && b.isEmpty()) return true;
T element_a = a.pop();
T element_b = b.pop();
try {
if (((element_a==null) && (element_b!=null)) || (!element_a.equals(element_b)))
return false;
return compareStacks(a, b);
} finally { // restore elements
a.push(element_a);
b.push(element_b);
}
}
In pseudo-code, you could do something like this:
boolean compareStacks(a, b) {
if (a.isEmpty() != b.isEmpty()) return false; // check if one is empty
if (a.isEmpty() && b.isEmpty()) return true; // check if both are empty
element_a = a.pop(); // grab elements and compare them
element_b = b.pop();
if (((element_a==null) && (element_b!=null)) || !element_a.equals(element_b)) {
a.push(element_a); // if they are not equal, restore them and return false
b.push(element_b);
return false;
}
result = compareStacks(a, b); // compare shortened stacks recursively
a.push(element_a); // restore elements
b.push(element_b);
return result; // return result from recursive call
}
With recursion it always helps to think of it as 2 parts, a "Setup" and a recursive function. Your setup would create the proper situation (create the two stacks, pass them in, etc) and then calls the recursive method and when the recursive method is done, report the results.
In your case you probably want this signature for the "recursive" method:
public boolean compareStacks(Stack one, Stack two)
If that method pops & compares the top tow elements of the stack, it can return false right then (saying they don't compare). If they do, you now have two stacks, each one shorter than before. You already know how to compare those two stacks, right (You just wrote the method to do so!).
at the end you can "Push" your one element back onto each stack to restore it's previous state before returning.
There will be a little trickiness in restoring the stack in the case where they don't compare, and ensuring that if the compareStack you call fails it properly passes that up to the previous state, even if the "current" compareStack succeeds, but those are implementation details--just thought I'd mention those so you don't overlook them.
There is a cute solution with Try/finally (no catch, return from within the try and push back onto the stack in the finally) that would make the code pretty slick, but it's easy enough without it.

Categories

Resources