Coding Bat CigarParty Ternary Operator Solution - java

public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend == false) {
return cigars >= 40 && cigars <= 60 ? true : false;
}
if (cigars >= 40) {
return isWeekend ? true : false;
}
else {
return false;
}
}
Does anyone have any feedback on how I could be more efficient with ternary operators?

As #codebod said, much of your code is redundant.
This is one way to solve it with ternary operators:
public boolean cigarParty(int cigars, boolean isWeekend) {
return (isWeekend) ? (cigars >= 40): (cigars >= 40 && cigars <= 60);
}
This is one way to solve it without ternary operators:
public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend){
return (cigars >= 40);
}else{
return (cigars >= 40 && cigars <= 60);
}
}

These ternary operators can be removed entirely. Each of your return statements already evaluates to the required boolean result. Your statements as written with the ternary operators essentially say: if true return true, else return false, which is redundant.
I think the most readable form that includes a ternary operator, if that's what's needed, is:
public boolean cigarParty(int cigars, boolean isWeekend) {
if (cigars < 40){
return false;
}
return isWeekend ? true : cigars <= 60;
}
This also eliminates the repeated comparison of cigars with 40.

You don't really need ternary operators at all. But you can do it like so.
if the cigars < 40, it is always false.
otherwise, return true if either of the subsequent conditions are true.
public static boolean cigarParty(int cigars, boolean isWeekend) {
return cigars < 40 ? false : (cigars <= 60 || isWeekend);
}
I would prefer the following:
if cigars < 40 it will return false and short circuit the expression.
if either of the others is true it will return true
public static boolean cigarParty(int cigars, boolean isWeekend) {
return cigars >= 40 && (cigars <= 60 || isWeekend);
}

Related

Why the first if statement is failing?

Edit: Apologize for confusing some of you, here is little more details.
I am very new to the stackoverflow. So I apologize in advance for a stupid questions.
I came across the below exercise in Udemy and my code is failing. Please help me understand why it is failing?
Description of the exercise:
Write a method shouldWakeUp that has 2 parameters.
1st parameter should of type boolean and be named barking it represents if our dog is currently barking
2nd parameter represents the hour of day and is of the type int with the name hourOfDay and has a valid range of 0-23
we have to wake up if the dog is barking before 8 or after 22 hours so that in that case return true, in all other case return false.
if the hourOfDay parameter is less than 0 or greater 23 return false
public class BarkingDog {
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
} else if (hourOfDay < 0 || hourOfDay > 23) {
}
return false;
}
}
Your first statement fails because you are not checking if it’s barking and conditions for less than 0 or greater than 23.
You need to do the following
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (barking) {
if ((hourOfDay > 0 && hourOfDay < 8) || (hoursOfDay > 22 && hoursOfDay <23)) {
return true;
}
}
return false;
}
Based on the comment:
"method call shouldWakeUp(false, -5) returned a value of "true" but "false" was expected
Its not very weird:
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
}
If hourOfDay = -5, it is
hourOfDay < 8
So it will return True. Since your 2nd if statement checks if it is smaller than 0, this might seems weird. But your 2nd if statement is never reached.
If a number is smaller than 0, it is also smaller then 5.
In order to fix this you can do the following:
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 0 || hourOfDay > 23) {
return false;
}
return true;
}
Now we check if the value is less than 0 (so -1,-2,-3,etc) or larger than 23 (so 24,25,26,etc) then we return false. In all other cases we return true (this means between 0 and 23)
Edit: ofc you should use the boolean (barking) you provide in the function to check the time and return accordingly as the assignment describes, but I left that out and think you can fix that yourself.
According to the description provided, your method should return false if the time is in invalid range i.e < 0 or > 23.
In your code, when you give invalid time range say -5, it checks against the first condition and the condition is satisfied because, -5 is lesser than 8. So it returns true. Generally what you should do is always put your guard conditions(which returns false) at first.
So, your code should become as this,
[Edited]
public class BarkingDog {
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 0 || hourOfDay > 23) {
return false;
} else if (hourOfDay >= 8 && hourOfDay <= 22) {
return false;
}
return barking;
}
}
Things to consider while writing these kinds of conditions
As said before, try to put all guard conditions at first. Hence it is called as guard. Think it of as a security dog infront of a building. It guards the method by checking all of the invalid checks at first returns the control immediately if it doesn’t satisfy.
Ordering of numerical check should be in ascending order. In your case the values(8) you checked against in your first condition is greater than the values(0). So you have to move this condition up a step. Actually this may confuse you in the beginning when you are using conditions with && or || Boolean operators.
These are some of the tips you can have.

Convert this java method without using if/loops

Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}

Simple logic not working or am I missing something?

I don't understand why the following class prints out:
true
false
I thought the output should be:
false
false
because this line prints false:
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
so this line should also print false:
System.out.println(in1To10(11, false));
What am I missing here? Here's the class.
public class TestClass {
public static void main(String[] args) {
System.out.println(in1To10(11, false));
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
}
public static boolean in1To10(int n, boolean outsideMode) {
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
return false;
}
}
You want to test if value is in the range 1 to 10 ?
If thats the case, change (n >= 1 || n <= 10) to (n >= 1 && n <= 10)
( true )
( true ) & ( true )
(true || false ) & ( true ) <--- false == false is true!
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
Look, is n >= 1? Yes, so it's true. true v p <-> true, so Java doesn't even check further. true /\ true <-> true so we enter if. return true;
Your code is in plain English:
if ((n is greater or equal to 1 OR smaller or equal 10) AND is the mode set to false)
return true
If you want it to return true if the number is between 1 and 10 incl, it would be:
if ((n is greater or equal to 1 AND smaller or equal 10) AND is the mode set to false)
return true
which in Java is:
if ((n >= 1 && n <= 10) && (outsideMode == false)) {
return true;
}
Also remember to use && and || as they are logical operators instead of | and & bitwise logical operators when dealing with boolean values.
so this line should also print false: System.out.println(in1To10(11, false));
No, this line should not print false. Although the first parameter, 11, indeed turns the expression n >= 1 || n <= 10 from your method into 11 >= 1 || 11 <= 10, which matches your other expression, the second parameter, false, turns outsideMode == false into false == false, while your other expression has true == false.
That is why the two outputs are different: the output from in1To10 is true because the comparison false == false produces true, while the output from main is false, because true == false produces false.
Note: your expression does not match its stated goal of checking if n is between 1 and 10, inclusive. You need to replace || with && to accomplish that.
I think you missed that in function in1to10, you are comparing (false == false) and in main you are comparing (true == false). And so is the result. Hope this helps.
Let's decompose the test in in1to10 :
Parameters : outsideMode = false; n = 11;
(n >= 1 || n <= 10) :=> (11 >= 1 || 11 <= 10) :=> (true || false) :=> so TRUE
outsideMode == false :=> false == false :=> so TRUE
In the end :
public static boolean in1To10(int n, boolean outsideMode) {
if ((TRUE) & (TRUE)) {
return true;
}
return false;
}
:=> return TRUE !
This will return true. How?
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
You are passing 11 and false to the function.
When it goes to inside the first condition it will check that n >= 1 mean 11 >= 1 that is true, so it will not check n<=10. Again it will check the second condition and your outsideMode is false,
That will be like this, (true) & (true)
hence the whole condition will be true and the funciton will return true.
Again the second condition,
(11 >= 1 || 11 <= 10) & (true == false)
It will return false. How?
As 11 >= 1 is true and again it will not check 11 <= 10, and right side is false.
So the condition will be become like this,
true & false that will be false.

Coding bat simple code logic in JAVA

Coding bat is a website to test the candidate's logic and reasoning abilities using JAVA or Python. I am trying the following problem and am unable to proceed:
Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
nearTen(12) → true
nearTen(17) → false
nearTen(19) → true
.
The code I have written is :
{
public boolean nearTen(int num) {
if (num==10 || num==1){
return true;}
else if (num<10){
return false;}
else if ((num+2)%10==0 || ((num-2)%10==0)){
return true;}
else if ((num+1)%10==0 || ((num-1)%10==0)){
return true;}
else{
return false;}
}
}
Can anyone of you please tell my mistake so that I can improve on the same?
You have to check if the modulo of the given number is either less that or equal to 2 (<= 2), or greater than or equal to 8 (>= 8).
You don't have to check for any special values, since there aren't any, they respond to the general logic of the question.
public boolean neatTen (int num) {
if (num%10 <= 2 || num%10 >= 8) {
return true;
} else {
return false;
}
}
If you had to take into account negative values, you would have to use Math.abs() to make the number positive, but that's a very small change to the code.
If you want to have it as a one-liner:
return (num%10 <= 2) ? true : (num%10 >= 8) ? true : false ;
Return true if remainder after dividing by 10 is 0, 1, 2, 8 or 9.
public boolean nearTen (int num) {
if (num%10 <= 2 || num%10 >= 8)
return true;
return false;
}
If I had understood the question right then you just need to use mod(%) and check if the reminder is <= 2 or >= 8.
public static boolean nearTen(int num) {
if (num==10 || num==1){
return true;
}
else if (num<10 && 10-num<2){
return true;
}
else if (num%10<=2 || num%10>=8){
return true;
}
else{
return false;
}
}

Return statement syntax

What do the symbols '?' and ':' mean in a return statement?
public boolean isItBigger(BigInteger num1, Long num2) {
return num1 == BigInteger.ONE || num2.intValue() > 0 ? true : false;
}
Also I think I have seen them in if statements.
Using ? and : is Java's ternary conditional operator (JLS 15.25). The result of the expression
aBoolean ? expr1 : expr2
is expr1 if aBoolean is true, else it's expr2.
In this case, it could be left off because it's unnecessary:
return num1 == BigInteger.ONE || num2.intValue() > 0;
It's a ternary operator. The following are equivalent
if (x == y)
x = 2;
else
x = 3;
and
x = (x == y) ? 2 : 3;
Your example code is silly though. First they're checking if the expression evaluates to true. Then, if it does, they return true. They could just as well return the result of expression itself, like so:
return num1 == BigInteger.ONE || num2.intValue() > 0;
this is called conditional/ternary operator
boolean-expression ? do-this-if-true : else-do-this
it is shortened form of
if (boolean-expression) {
do-this
} else{
do-this
}

Categories

Resources