monkeyTrouble

Programming problem at

http://codingbat.com/prob/p181646

We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble.
monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false

 

My Solution

Both smiling and both not smiling , that is both true and both false points my brain towards the XOR gate

First i wrote

return (aSmile ^ bSmile );

which gave result exatly opposite to what was required , so i read the problem again

i had to change the code with

return !(aSmile ^ bSmile );

The complete solution is

 

public class monkeyTrouble {
    public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
        return !(aSmile ^ bSmile);
    }
}

 

The official solution was

 

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
if (aSmile && bSmile) {
return true;
}
if (!aSmile && !bSmile) {
return true;
}
return false;
// The above can be shortened to:
// return ((aSmile && bSmile) || (!aSmile && !bSmile));
// Or this very short version (think about how this is the same as the above)
// return (aSmile == bSmile);
}


Comparison / Analysis

Lesson learnt is to read the problem carefully and to retest your solution with dry run for possible outputs. I am going to write unit tests for testing the programs in future


I found one website which explain all the logical operators in Java


http://www.sap-img.com/java/java-boolean-logical-operators.htm

No comments:

Post a Comment

Please share your views and comments below.

Thank You.