Can anyone spot the error that i am making? - java

All test case is running successfully except one which is in1To10(9, true) → false.
Question:
Given a number n, return true if n is in the range 1..10,
inclusive. Unless outsideMode is true, in which case return true if
the number is less or equal to 1, or greater or equal to 10.
in1To10(5, false) → true
in1To10(11, false) → false
in1To10(11, true) → true
My Solution:-
public boolean in1To10(int n, boolean outsideMode) {
if(n>=1&&n<=10){
return true;
}
else if(outsideMode==true&&(n<=1||n>=10)){
return true;
}else
return false;
}

As you have mentioned in problem the return boolean value is based on boolean value of outsideMode and the range (1-10) value
But in your program the first return statement value is decided by only the range criteria you did't test the boolean value of outsideMode.
1. Solution :
Either swap the second if(condition) with first if(condition)
public boolean in1To10(int n, boolean outsideMode) {
if((outsideMode==false)&&(n>=1&&n<=10)){
return true;
}
else if(outsideMode==true&&(n<=1||n>=10)){
return true;
}else
return false;
}
2.Solution:
include the outsideMode with first if(condition) same like second if(condition)
public boolean in1To10(int n, boolean outsideMode) {
if(outsideMode==true&&(n<=1||n>=10)){
return true;
}
else if(n>=1&&n<=10){
return true;
}else
return false;
}

When you say "all test cases are running successfully", that is rather misleading since you have too few test cases.
For each interesting integer comparison you need 2 test cases: one in which the comparison succeeds and one in which it fails. As test data you should pick the two integers that make the difference. For example, if the condition is n > 10, you should use 10 and 11 as test data.
In your scenario you have a boolean, and in each case of that boolean you have two integer conditions. Altogether, that makes 2 * 2 * 2 = 8 test cases. That is much more than the 3 test cases that you currently have, but it's necessary.
By testing your code systematically you will produce more reliable code than without these tests, even if it takes some time. But in return you get more confidence in the code, and that is worth it.
Further reading: test coverage, condition coverage.

First of all outsideMode is a boolean so just writte outisdeMode&&(n<=1||n>=10)
Your error is that
if(n>=1&&n<=10){
return true;
}
Will be executed befor
else if(outsideMode==true&&(n<=1||n>=10))
Because 9 >= 1 && 9 <= 10 which means that it will return true
Swap them and you will be fine
public boolean in1To10(int n, boolean outsideMode) {
if(outsideMode&&(n<=1||n>=10)){
return true;
}
else if(!outsideMode&&n>=1&&n<=10){
return true;
}else
return false;
}

Related

How can I fix my code to solve this case?

There is a Java coding question which returns true if the given non-negative number is 1 or 2 less than a multiple of 20. For example 38 and 39 it returns true, but 40 returns false.
My code:
public boolean less20(int n){
if(n%20==0){
return false;
}else if(n>20 && n%20!=0){
return false;
}else if(20-n>2){
return false;
}else if((n+1)%20!=0||(n+2)%20!=0){
return true;
}else{
return true;
}
}
The code works on most cases, but some of them does not work at all, such as n=58 or n=59.
How can I fix my code and use the easiest way to solve this question?

Java boolean method return

I have a boolean method in my Java program and I'm wondering why NetBeans is recommending making this change to my code:
return isPrime != 0;
What I wrote was:
if (isPrime == 0) {
return false;
}
else{
return true;
}
Both work correctly but I cannot understand the logic behind the change NetBeans is suggesting. Neither true or false is being returned. Could someone explain to me the logic behind this? Thanks
NetBeans is exactly correct. The expression is a boolean. You can easily prove it by making the change and trying it.
What value does 0 != 0 evaluate to? (Hint: it's false). What about 1 != 0? (Hint: it's true).
Is that not what your more verbose code says?
Instead of
if (isPrime == 0) {
return false;
} else {
return true;
}
try
return (isPrime != 0);
It is the same thing, I'll show you the refactoring path. Starting with
if (isPrime == 0) {
return false;
} else {
return true;
}
is the same as
if (isPrime != 0) {
return true;
} else {
return false;
}
which can be reduced by substitution, substituting 'isPrime != 0' with the function 'doIsPrime()'
private boolean doIsPrime() {
return isPrime != 0;
}
substituting in
if (doIsPrime()) {
// guaranteed to be the same as above!
return doIsPrime();
} else {
return doIsPrime();
}
which can have both blocks reduced (as duplicated code)
if (doIsPrime()) {
}
return doIsPrime();
And reduced further by removing the if statement around the empty block
return doIsPrime();
Now undo the substitution 'doIsPrime()' back to 'isPrime != 0'
return isPrime != 0;
There was no need to really do the substitution; but, I find it better shows off the reasoning the if statement is redundant.
Neither true or false is being returned.
False. The result of the comparison isPrime != 0, a boolean is being returned, either true or false.
Could someone explain to me the logic behind this?
The first code is equivalent to the second code. If isPrime is 0, then return false, else return true. The != operator will yield false if isPrime is 0, and true if it isn't 0.
It means its returning the result of the predicat isPrime != 0
If isPrime = 0, then the predicat is false, therefore it return false
If isPrime != 0, then the predicat is true, therefore returning true
It's just to reduce code.
The expression isPrime != 0 returns a boolean. It is false if isPrime == 0 and true if isPrime != 0. Thus you can save the if statement and some lines of code.
Just to add to what's already said:
Though your solution and NetBeans recommended approach are exactly correct, one other approach would also be:
if (isPrime == 0) {
return false;
}
return true;
I don't know what NetBeans would suggest with this approach but I guess that it would propose the same recommendation as it did above.

Can we use .contains(BigDecimal.ZERO) when reading a list in JAVA?

Can we use .contains(BigDecimal.ZERO) when reading a list in JAVA ??
I am trying:
if (selectPriceList.contains(BigDecimal.ZERO)) {
return true;
}
return false;
But it always returns false.
This seems to work but does it need correction?
BigDecimal zeroDollarValue = new BigDecimal("0.0000");
if (selectPriceList.contains(zeroDollarValue)) {
return true;
}
return false;
The problem occurs because the scale, the number of digits to the right of the decimal point, of BigDecimal.ZERO is set to 0, while the scale of zeroDollarValue is 4.
The equals method of BigDecimal compares both the scale and the value - if either are different, it returns false.
You can probably use
return selectPriceList.contains(BigDecimal.ZERO.setScale(4));
Assuming that all of your prices go out to four decimal places. If not, you might have to use
for(BigDecimal bd : selectPriceList) {
if(bd.compareTo(BigDecimal.ZERO) == 0) {
return true;
}
}
return false;
For more information, see the documentation.

recursive search in java

I have the following problem:
I have a hashset of Pairs. Pair is a pair of ints. the pair represents "likes".
let's say my set is :<1,2>,<2,1>,<3,1>,<6,7>,<5,7>,<2,6>
this means 1 likes 2 and 2 likes 1 and 3 likes 1 and so on...
What I'm requested to do is to look at those relations as a graph and given two numbers let's say 2 and 6 I have to find whether there is a route in a graph from 2 to 6 with at most 5 edges connecting between them...
how to write a short recursive method that calculates if the route exists?
I wrote the following code:
private boolean findPath(int from, int to, int count){
System.out.println(from+" "+to+" "+count);
if(from==to && count<=5)
return true;
if(count>5)
return false;
Iterator<CookingParty.Pair> iter=likesSet.iterator();
while(iter.hasNext()){
Pair curr=iter.next();
if(curr.likes==from && curr.liked==to){
return true;
}
if(curr.likes==from)
return findPath(curr.liked, to, count+1);
}
return false;
}
the problem is that it won't continue going over the rest of the possibilities once one was found to be wrong.
how can I change it to work?
this is the update:
private boolean findPath(int from, int to, int count){
System.out.println(from+" "+to+" "+count);
if(from==to && count<=5)
return true;
if(count>5)
return false;
Iterator<CookingParty.Pair> iter=likesSet.iterator();
boolean found=false;
while(iter.hasNext() && !found){
Pair curr=iter.next();
if(curr.likes==from && curr.liked==to){
found=true;
return found;
}
if(curr.likes==from)
return findPath(curr.liked, to, count+1);
}
return found;
}
Currently you return as soon as you find a pair where curr.likes == from. To explore also other paths, you mustn't immediately return in the while loop, but while you haven't yet found a path, check for further possibilities.
boolean found = false;
while(iter.hasNext() && !found){
// check a path
}
return found;
Re update: You are still returning in the loop. That's okay in the case where you found a path, but you absolutely must not return in the general case. If curr.likes == from and curr.liked != to, check that path and update the boolean, do not return. Return after the loop has finished.
To search for a path in a graph you can use Depth-First or Breadth-First search. Depth-first is traditionally recursive because it uses a stack. Have a look at the pseudocode here:
http://en.wikipedia.org/wiki/Depth-first_search#Pseudocode

Whats wrong with my syntax and am i doing this efficiently?

I'm trying to make a method that will tell me weather or not it is true or false that a number is prime. here's the code:
class prime
{
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
prime (a, b-1) ;
}
else
{
return true;
}
}
public static void main (String[] arg)
{
System.out.println (prime (45, 45)) ;
}
}
when i try to compile this i get this error message:
prime.java:23: missing return statement
}
^
1 error
I could be misinterpreting what the error message is saying but it seems to me that there isn't a missing return statement since i have a return statement for every possible set of conditions. if a is 0 then it returns false, if it isn't then it checks to see if a is dividable by b if it is then it returns if not then if b is greater than 1 it starts over again. if b isn't greater than 1 it also returns.
Also it seems a bit messy to have to
make this method take two ints that
are the same int.
What is wrong with my syntax/ why am i getting the error message? Is there a way to make it so that the method that i use in main only has to take one int (perhaps another method splits that int into two clones that are then passed to public static boolean primeproper?
or is there a more effective way of
going about this that i'm missing
entirely?
In your prime function, there are four possible code paths, one of which doesn't return anything. That is what the error message is complaining about. You need to replace:
prime (a, b-1) ;
with:
return prime (a, b-1) ;
in the else if (b>1) case.
Having said that, this is actually not a good way to calculate if a number is prime. The problem is that every recursive call allocates a stack frame and you'll get into serious stack overflow problems if you're trying to work out whether 99,999,999 is a prime number?
Recursion is a very nice tool for a certain subset of problems but you need to be aware of the stack depth. As to more efficient solutions, the are many tests you can carry out to determine a number is not prime, then only check the others with a brute force test.
One thing you should be aware of is to check divisibility against smaller numbers first since this will reduce your search scope quicker. And don't use divide where multiply will do, multiplication is typically faster (though not always).
And some possibly sneaky tricks along the lines of:
every number other than 2 that ends in 2, 4, 6, 8 or 0 is non-prime.
every number other than 5 that ends in 5 is non-prime.
Those two rules alone will reduce your search space by 60%. Assuming you get your test number as a string, it's a simple matter to test the last digit of that string even before converting to an integral type.
There are some more complex rules for divisibility checks. If you take a multiple of 9 and sum all the digits to get a new number, then do it again to that number, then keep going until you have a single digit, you'll find that it's always 9.
That will give you another 10% reduction in search space albeit with a more time-expensive check. Keep in mind that these checks are only advantageous for really large numbers. The advantages are not so great for, say, 32-bit integers since a pre-calculated bitmap would be much more efficient there (see below).
For a simplistic start, I would use the following iterative solution:
public static boolean prime (int num) {
int t = 2;
while (t * t <= num) {
if ((num % t) == 0) {
return false;
}
t++;
}
return true;
}
If you want real speed in your code, don't calculate it each time at all. Calculate it once to create a bit array (one of the sieve methods will do it) of all primes across the range you're interested in, then simply check your values against that bit array.
If you don't even want the cost of calculating the array every time your program starts, do it once and save the bit array to a disk file, loading it as your program starts.
I actually have a list of the first 100 million primes in a file and it's easier and faster for me to use grep to find if a number is prime, than to run some code to calculate it :-)
As to why your algorithm (fixed with a return statement) insists that 7 is not prime, it will insist that every number is non-prime (haven't checked with negative numbers, I'm pretty sure they would cause some serious problems - your first check should probably be if (a < 1) ...).
Let's examine what happens when you call prime(3,3).
First time through, it hits the third condition so calls prime(3,2).
Then it hits the second condition since 3 % (2-1) == 0 is true (N % 1 is always 0).
So it returns false. This could probably be fixed by changing the third condition to else if (b>2) although I haven't tested that thoroughly since I don't think a recursive solution is a good idea anyway.
The following complete code snippet will do what you need although I appreciate your curiosity in wanting to know what you did wrong. That's the mark of someone who's actually going to end up a good code cutter.
public class prime
{
public static boolean isPrime (int num) {
int t = 2;
while (t * t <= num) {
if ((num % t) == 0) {
return false;
}
t++;
}
return true;
}
public static void main (String[] arg)
{
System.out.println (isPrime (7)) ;
}
}
You seem to be under the impression that because the recursion will eventually find a base-case which will hit a return statement, then that return will bubble up through all of the recursive calls. That's not true. Each recursive call must pass out the result like this:
return prime(a, b - 1);
If b is larger than 1, your function won't return anything.
May it be return prime (a, b-1) ; ?
To improve efficiency, think more about your conditions. Do you really need test every factor from 2 to N? Is there a different stopping point that will help tests of prime numbers complete more quickly?
To make a better API, consider making the recursive method private, with a public entry point that helps bootstrap the process. For example:
public static boolean prime(int n) {
return recurse(n, n);
}
private static boolean recurse(int a, int b) {
...
}
Making a method private means that it can't be called from another class. It's effectively invisible to users of the class. The intent here is to hide the "ugly" extra parameter by providing a public helper method.
Think about the factors of some composite numbers. 10 factors to 5×2. 12 factors to 6×2. 14 factors to 7×2. Now think about 25. 25 factors to 5×5. What about 9? Do you see a pattern? By the way, if this isn't homework, please let me know. Being this didactic is hard on me.
In answer to why 7 isn't working, pretend you're the computer and work through your logic. Here's what you wrote.
class prime
{
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
// Have to add the return statement
// here as others have pointed out!
return prime(a, b-1);
}
else
{
return true;
}
}
public static void main (String[] arg)
{
System.out.println (prime (45, 45)) ;
}
}
So let's start with 7.
if(7 == 0) // not true, don't enter this block
else if(7 % 6 == 0) // not true
else if(7 > 1) // true, call prime(7, 6)
if(7 == 0) // not true, don't enter this block
else if(7 % 5 == 0) // not true
else if(6 > 1) // true, call prime(7, 5)
if(7 == 0) // not true, don't enter this block
else if(7 % 4 == 0) // not true
else if(5 > 1) // true, call prime(7, 4)
... keep going down to calling prime(7, 2)
if(7 == 0) // not true, don't enter this block
else if(7 % 1 == 0) true, return false
When you get down to calling prime(n, 2), it will always return false because you have a logic error.
Your recursive method must return a value so it can unroll.
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if (a%(b-1) == 0)
{
return false;
}
else if (b>1)
{
return prime (a, b-1) ;
}
else
{
return true;
}
}
I might write it a different way, but that is the reason that you are not able to compile the code.
I think the original question was answered already - you need to insert return in the body of else if (b>1) - I just wanted to point out that your code still will crash when given 1 as the value for b, throwing an ArithmeticException since a%(b-1) will be evaluated to a%0, causing a division by zero.
You can avoid this by making the first if-statement if (a == 0 || b == 1) {}
This won't improve the way the program finds primes, it just makes sure there is one less way to crash it.
Similar to #paxdiblo's answer, but slightly more efficient.
public static boolean isPrime(int num) {
if (num <= 1 || (num & 1) == 0) return false;
for (int t = 3; t * t <= num; t += 2)
if (num % t == 0)
return false;
return true;
}
Once it is determined that the number is not even, all the even numbers can be skipped. This will halve the numbers which need to be checked.

Categories