Reputation: 122
I use this code to find closest number in array, but this method also return number below target number. So if target is 5 and array have 4 a 7 it will return 4. How can i change this code to show clostest number above target.
public static int findClosest(Integer[] arr, int target) {
int idx = 0;
int dist = Math.abs(arr[0] - target);
for (int i = 1; i < arr.length; i++) {
int cdist = Math.abs(arr[i] - target);
//TODO MAKE CLOSEST NUMBER BE ABOVE TARGET
if (cdist < dist) {
idx = i;
dist = cdist;
}
}
Log.e("FIND!!!", "CLOSEST MINUTE IS --->" + arr[idx]);
int minute_of_day = arr[idx];
return minute_of_day;
}
Upvotes: 1
Views: 1759
Reputation: 19545
Just fix the code according to your requirement: find the minimal number of those above the target. Also it would make sense to check for null
values in the input array.
public static Integer findClosestAbove(Integer[] arr, int target) {
Integer min = null;
for (Integer x : arr) {
if (x != null && x > target && (min == null || min > x)) {
min = x;
}
}
return min; // may be null
}
Similar solution using Java Stream API is as follows:
public static Integer findClosestAboveStream(Integer[] arr, int target) {
return Arrays.stream(arr)
.filter(x -> x != null && x > target)
.min(Integer::compareTo) // Optional<Integer>
.orElse(null); // or orElseGet(() -> null)
}
Test:
Integer[] arr = new Integer[]{1, 2, null, 7, 4};
System.out.println("findClosest:\t" + findClosestAbove(arr, 5));
System.out.println("findClosest2:\t" + findClosestAboveStream(arr, 5));
Output:
findClosest: 7
findClosest2: 7
Upvotes: 4
Reputation: 2660
One alternative is the method below:
public static int findClosest(Integer[] arr, int target) {
int temp = Integer.MAX_VALUE;
for(int i: arr){
if(i > target && i < temp){
temp = i;
}
}
return temp;
}
The way this code works is that it starts by initializing an integer, temp
to the largest possible integer. Then, we start looping through arr
and whenever we find a value greater than the target but less than the current value of temp
, we set temp
equal to that value. Finally, after we iterate through, we return that value.
Upvotes: 1
Reputation: 446
Here's one way to do it (requires importing java.util package) - sort the array in ascending order, then find the first higher element, if it exists. A higher value may not exist in the array, so that error has to be handled.
public static int findClosestHigher(Integer[] arr, int target) throws NoSuchElementException {
List<Integer> arrList = Arrays.asList(arr);
Collections.sort(arrList);
for (int element : arrList) {
if (element > target) {
System.out.println("FOUND!!! CLOSEST HIGHER IS --->" + element);
return element;
}
}
throw new NoSuchElementException();
}
Upvotes: 1