Convert this java method without using if/loops - java

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));
}

Related

Coding Bat CigarParty Ternary Operator Solution

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);
}

Displays if a whole number (>0) is divisible by 2 and 3

I have tried to do this in java however the && symbols keep on giving error.
Below is the code that I used:
int d = 18;
{
if ((d % 2) && (d% 3));
{
System.out.println("True!");
}
{
System.out.println("False!");
}
}
This is my code. I am not sure why its not working. Thanks
The error message is The operator && is undefined for the argument type(s) int, int. #
I have got it to work now. I have an else error . "The error says Syntax error on token "else", delete this token"
public class CS1702_Lab3_4 {
int d = 18;
{
if ((d % 2 == 0) && (d % 3 == 0));
{
System.out.println("True!");
}
else
{
System.out.println("False");
}
}
}
Also when I add an else it says Syntax error on token "else", delete this token
Please learn about the modulus operator, and how to check divisibility in java.
if ((d % 2 == 0) && (d % 3 == 0))
{
System.out.println("True!");
}
Also, you had a rogue semi-colon at the end of your if statement.
EDIT: Fixed code
public class CS1702_Lab3_4 {
public static void main(String[] args) { // Entry into our program
int d = 18;
if ((d % 2 == 0) && (d % 3 == 0)) {
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
}
}
I'd recommend looking at some basic Java tutorials, however the fixes I applied included:
Contained your code inside of a method, specifically the main method, which is the entry point to a runnable Java application. Java is not a procedural language, code outside of variable, method, class, package and import declarations need to be contained inside of a method
Fixed syntax on your if statement, removed rogue semi colon
if ((d % 2) && (d% 3)); you have a semicolon ; at the end,
remove it.
If d == 18, then ((d%2) && (d%3)) = (0 && 0) = 0 So in this
case, What java sees is: if(0){ // ... }
If I remember correctly, this is valid in C/C++, but not in Java. That is why you get error.
Anyways, to fix the problem, you can do this:
if (((d % 2) == 0) && ((d % 3) == 0)){
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
if condition expects boolean. Mod operation would not return boolean, this is why compiler is intelligent and gives you this error.
if you try to run
if (1 && 2) // this will give you an error as well.
The expressions need to evaluate to a boolean (either true or false) in order to understand operators like && and ||
Moreover, you statement will not work since you are using ; at the end.

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.

Primality Check

Every prime number is in the form of 6k+1 or 6k-1. In order to check if a number is prime or not we can use the below algorithm. I have seen programs that are written based on these algorithms.
public boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
But I don't understand what would have been the problem if we had written code in the following manner:
public boolean isPrime(int number){
boolean primeFlag = false;
if(number == 0 || number ==1){
return primeFlag;
}
if(number == 2 || number == 3){
primeFlag = true;
}
if((number+1)%6 == 0){
primeFlag = true;
}
if((number-1)%6 == 0){
primeFlag = true;
}
return primeFlag;
}
By this we can reduce the time complexity to O(1) compared to O(root(n)). Please let me know if am heading towards wrong direction.
It is correct to say that every prime (except for 2 and 3) has a remainder of 1 or 5 when divided by 6 (see this page for a deeper explanation). However, the opposite is not true. Not every number that has a remainder of 1 or 5 when divided by 6 is a prime.
Take 35 for example. It has a remainder of 5 when divided by 6, however it is not a prime (35 = 5 x 7).

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;
}
}

Categories

Resources