I am wondering how you would write a simple java method finding the closest Integer to a given value in a sorted Integer list.
Here is my first attempt:
public class Closest { private static List<Integer> integers = new ArrayList<Integer>(); static { for (int i = 0; i <= 10; i++) { integers.add(Integer.valueOf(i * 10)); } } public static void main(String[] args) { Integer closest = null; Integer arg = Integer.valueOf(args[0]); int index = Collections.binarySearch( integers, arg); if (index < 0) /*arg doesn't exist in integers*/ { index = -index - 1; if (index == integers.size()) { closest = integers.get(index - 1); } else if (index == 0) { closest = integers.get(0); } else { int previousDate = integers.get(index - 1); int nextDate = integers.get(index); if (arg - previousDate < nextDate - arg) { closest = previousDate; } else { closest = nextDate; } } } else /*arg exists in integers*/ { closest = integers.get(index); } System.out.println("The closest Integer to " + arg + " in " + integers + " is " + closest); } }
What do you think about this solution ? I am sure there is a cleaner way to do this job.
Maybe such method exists somewhere in the Java libraries and I missed it ?
We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.
Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .
A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference. An efficient solution is to use Binary Search.
try this little method:
public int closest(int of, List<Integer> in) { int min = Integer.MAX_VALUE; int closest = of; for (int v : in) { final int diff = Math.abs(v - of); if (diff < min) { min = diff; closest = v; } } return closest; }
some testcases:
private final static List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); @Test public void closestOf21() { assertThat(closest(21, list), is(20)); } @Test public void closestOf19() { assertThat(closest(19, list), is(20)); } @Test public void closestOf20() { assertThat(closest(20, list), is(20)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With