get closest value to a number in array

In Java 8:

List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());

int n = 490;

int c = list.stream()
            .min(Comparator.comparingInt(i -> Math.abs(i - n)))
            .orElseThrow(() -> new NoSuchElementException("No value present"));

Initially, you can use a List instead of an Array (lists have much more functionality).


int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
for(int c = 1; c < numbers.length; c++){
    int cdistance = Math.abs(numbers[c] - myNumber);
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

Always initialize your min/max functions with the first element you're considering. Using things like Integer.MAX_VALUE or Integer.MIN_VALUE is a naive way of getting your answer; it doesn't hold up well if you change datatypes later (whoops, MAX_LONG and MAX_INT are very different!) or if you, in the future, want to write a generic min/max method for any datatype.


you are very close. I think the initial value of 'distance' should be a big number instead of 0. And use the absolute value for the cdistance.

Tags:

Java

Arrays