Reputation: 35
I have a small problem, but I hope somebody can help. Let's say that I have an array of integers, something like this:
int[] = {65, 75, 85}
And the program takes an integer input from the user, and the output will be the closest number from the array.
For example: If the user inputs 68, the output will be 65, since 65 is the closest number. Or if the user inputs 100 the output will be 85, since 85 is the closest.
EDIT: This is NOT homework. I program for myself not for anyone else :P
Thanks in advance, Martin
Upvotes: 1
Views: 517
Reputation: 533680
If the array is sorted, a more efficient approach is to use a binary search. This takes O(log n) time instead of O(n) elements, as it doesn't need to examine every value.
public static void main(String... args) {
int[] values = {65, 75, 85};
for (int find : new int[]{60, 68, 74, 88}) {
int result = closest(find, values);
System.out.println(find + " => " + result);
}
}
private static int closest(int find, int... values) {
int index = Arrays.binarySearch(values, find);
if (index >= values[0])
return index;
if (index == -1)
return values[0]; // closest
index = -index - 2;
if (index + 1 >= values.length)
return values[values.length - 1]; // closest
final int v0 = values[index];
final int v1 = values[index + 1];
return Math.abs(v0 - find) <= Math.abs(v1 - find) ? v0 : v1;
}
prints
60 => 65
68 => 65
74 => 75
88 => 85
Upvotes: 3
Reputation: 425208
The important thing is to compare the absolute differences.
Try this:
public int getClosest(int[] array, int input) {
int lowestDiff = Integer.MAX_VALUE;
int result = 0;
for (int i : array) {
int diff = Math.abs(input - i); // use API to get absolute diff
if (diff < lowestDiff) {
lowestDiff = diff;
result = i;
}
}
return result;
}
This code will return 0
if the array is empty.
Note: It is possible the input and array element is more than Integer.MAX_VALUE
apart. You may want to code for this.
Upvotes: 2
Reputation: 47607
public int getClosest(int input) {
int ret = -1;
for(int i=;i<array.length;i++) {
if (ret==-1 || Math.abs(array[i]-input)<Math.abs(array[ret]-input)) {
ret = i;
}
}
if (ret>-1)
return array[ret];
else
// To do
}
Upvotes: 0