Reputation: 13
I have an exercise in Java, writing a method (as followed) that receives as parameters an array with numbers and int x and returns true if there is in the array pair of numbers (not has to be in the following order) that its absolute difference is bigger than x.
for example for the array {1, 5, 2, 18, 4, 2, 11} and I can use one loop only. thank you for your help
public boolean difference (int[] a, int x)
Upvotes: 0
Views: 908
Reputation: 51511
Finding the largest difference between all pairs of numbers in an array is the same as finding the difference between the largest and smallest value. So you only need to find the largest and smallest value. Naturally, Java does this for you already:
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class Main {
public static void main(String[] args) {
int[] a = {1, 5, 2, 18, 4, 2, 11};
System.out.println(difference(a, 16));
System.out.println(difference(a, 17));
}
public static boolean difference(int[] a, int x) {
IntSummaryStatistics stat = Arrays.stream(a).summaryStatistics();
return (stat.getMax() - stat.getMin()) > x;
}
}
This produces the following output:
true false
Upvotes: 0
Reputation: 40057
Here is a slightly different approach.
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7};
System.out.println(difference(5,a));
}
static boolean difference(int[] a, int x) {
int min = a[0];
int max = min;
for (int i = 1; i < a.length; i++) {
int v = a[i];
if (v < min) {
min = v;
} else if (v > max) {
max = v;
}
// check here since it may not be
// necessary to iterate thru all values.
if (max - min > x) {
return true;
}
}
return false;
}
It is optimized in several ways.
delta
of min and max
is checked on each iteration since it may not be necessary to iterate over the entire list.max > min
, the absolute value is implicit, even for negative numbers.Upvotes: 0
Reputation: 74730
Use one loop to iterate the array
When the loop is finished work out the difference between min and max
I haven't written the java for you because I think this is an academic exercise, possibly homework. You'll get more out of it as a learning exercise if you do it yourself - take this algorithm, put it as comments and write the code for it. We (and your supervisor) will be here for you if you get stuck. Think of the comments as like when doing an exam and the invigilator/tutor says "show your working" - showing your working is important because:
Always write comments
Upvotes: 1
Reputation: 363
Algorithm : Have a smallest and largest variable initialised to smallest and greatest possible values. Loop through all elements and if smaller than smallest or greater than greatest update the respective variables. Then at the end of the loop compare x to greatest - smallest.
Upvotes: 1