Reputation: 1
i have the following task to do: write a method that gets an array as a parameter and an int number. the method returns true if there is a difference between 2 numbers in the array that its difference is bigger than the number variable value. notice that you can loop the array only once. so i wrote:
public class difference
{
public boolean difference(int[] a, int x)
{
int firstNum=a[0];//3
boolean answer=false;
for (int i=1;i<a.length;i++)
{
if (Math.abs(firstNum)-(Math.abs(a[i]))>Math.abs(x)) {
answer=true;
break;
}
}
return answer;
}
public static void main(String[]args)
{
difference test= new difference();
int[] array={3,4,6};
System.out.println(test.difference(array,0));
}
}
but for some reason this prints me false instead of true why?
Upvotes: 0
Views: 101
Reputation: 129
Your program is not the solution at the problem. There are two solutions at least, the first is O(n^2) and require to have two for loops to compare all the elements between them self. The second solution that you should use and that the problem force you to choose because it says that you can loop the array only once, it is to find in one for loop the minimum and the maximum of the array and control their difference. If their difference is more than the given number return true otherwise false.
Upvotes: 0
Reputation: 17890
Math.abs(firstNum)-(Math.abs(a[i])
must be
Math.abs(firstNum - a[i])
You should get the abs
of the difference and not each number.
But, what you are doing is abs(3) - abs(4)
= -1
which is less than 0. (similar thing for the others)
[...]if there is a difference between 2 numbers in the array that its difference is bigger than the number variable value
But you are only comparing the first number with each other...
If you need to find if two numbers exist such that the difference among them is greater than the passed integer, find the min and the max and find the difference between them (Thanks to @NeplatnyUdaj for correcting me)
Upvotes: 2