37

I have an array of positive/negative ints

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers[4] = 500;
numbers[5] = -100;
numbers[6] = -200;
numbers[7] = 532;
numbers[8] = 6584;
numbers[9] = -945;

Now, I would like to test another int against this array, and return the number that is closest to the int.

For example if I used the number 490 i would get back item #4 from numbers 500 what is the best way to do something like this?

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

That doesn't work. Any suggestions on a good method to do this?

3
  • 1
    cdistance = numbers[c] - myNumber. You're not taking the absolute value. Nov 10, 2012 at 2:47
  • 3
    You need to start out with distance equal to some very large number. Otherwise, cdistance will never be less than it. Also, you need to take the absolute value of cdistance before comparing. Nov 10, 2012 at 2:49
  • look at the answers which uses binary search. it's simple and efficient.
    – Diablo
    May 19, 2022 at 9:25

13 Answers 13

51
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.

2
  • 3
    -1 For the "naive" comment. It's guaranteed to give you the right answer with the least amount of code. The scenarios you describe are basically gold plating. Jun 12, 2015 at 4:23
  • @Chris Hayes Hai- I have a similar array. [0, 0, 215, 230, 243, 252] If my number is 225. I wanted assign for 215 (theNumber). In the above it gives me 230 instead because it is the closest. How to get this in this case ? thank you. Feb 24, 2021 at 11:32
35

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).

2
  • How do you set a distance max ?
    – Ayfri
    Apr 25, 2020 at 11:47
  • no need to create a separate Integer list. just convert the IntStream to Stream<Integer> . Arrays.stream(numbers) .boxed() .min(Comparator.comparingInt(i -> Math.abs(i - n))) .orElseThrow(NoSuchElementException::new);
    – Diablo
    May 19, 2022 at 10:08
4

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.

3

cdistance = numbers[c] - myNumber. You're not taking the absolute value of the difference. If myNumber is a lot greater than numbers[c] or if numbers[c] is negative, the comparison will register as the "minimum difference".

Take for example the case where numbers[c] = -34200. numbers[c] - myNumber would then be -34690, a lot less than the distance.

Also, you should initialize distance to a large value, as no solution has been found at the start.

3
int valueToFind = 490;

Map<Integer, Integer> map = new HashMap();

for (int i = 0, i < numbers.length; i++){
    map.put(Math.abs(numbers[i] - valueToFind), numbers[i]);
}

List<Integer> keys = new ArrayList(map.keySet());
Collections.sort(keys);

return map.get(keys.get(0));
0
2

You can tweak the good old binary search and implement this efficiently.

Arrays.sort(numbers);
nearestNumber = nearestNumberBinarySearch(numbers, 0, numbers.length - 1, myNumber);

private static int nearestNumberBinarySearch(int[] numbers, int start, int end, int myNumber) {
    int mid = (start + end) / 2;
    if (numbers[mid] == myNumber)
        return numbers[mid];
    if (start == end - 1)
        if (Math.abs(numbers[end] - myNumber) >= Math.abs(numbers[start] - myNumber))
            return numbers[start];
        else
            return numbers[end];
     if(numbers[mid]> myNumber)
        return nearestNumberBinarySearch(numbers, start,mid, myNumber);
     else
         return nearestNumberBinarySearch(numbers,mid, end, myNumber);

}
1
1

One statement block to initialize and set the closest match. Also, return -1 if no closest match is found (empty array).

 protected int getClosestIndex(final int[] values, int value) {
    class Closest {
        Integer dif;
        int index = -1;
    };
    Closest closest = new Closest();
    for (int i = 0; i < values.length; ++i) {
        final int dif = Math.abs(value - values[i]);
        if (closest.dif == null || dif < closest.dif) {
            closest.index = i;
            closest.dif = dif;
        }
    }
    return closest.index;
}
1
  • why would you use a nested Class, i m just curious !
    – Sikorski
    May 13, 2017 at 9:14
1
public int getClosestToTarget(int target, int[] values) {

    if (values.length < 1)
        throw new IllegalArgumentException("The values should be at least one element");
    if (values.length == 1) {
        return values[0];
    }
    int closestValue = values[0];
    int leastDistance = Math.abs(values[0] - target);
    for (int i = 0; i < values.length; i++) {
        int currentDistance = Math.abs(values[i] - target);
        if (currentDistance < leastDistance) {
            closestValue = values[i];
            leastDistance = currentDistance;
        }
    }
    return closestValue;
}
1

Kotlin is so helpful

fun List<Int>.closestValue(value: Int) = minBy { abs(value - it) }

val values = listOf(1, 8, 4, -6)

println(values.closestValue(-7)) // -6
println(values.closestValue(2)) // 1
println(values.closestValue(7)) // 8

List doesn't need to be sorted BTW

1
  • This doesn't work if between -1 and 1, the desired/closest number is 1 and not -1.
    – Dr.jacky
    May 19, 2022 at 15:43
0

I did this as an assignment for my course, and I programmed it in Ready to Program Java, so sorry if its a bit confusing.

// The "Ass_1_B_3" class.
import java.awt.*;
import hsa.Console;

public class Ass_1_B_3
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        int [] data = {3, 1, 5, 7, 4, 12, -3, 8, -2};
        int nearZero = 0;
        int temp = 0;
        int temp2 = data[0];

        for (int i = 0; i < data.length; i++)
        {
            temp = Math.abs (data[i]);
            nearZero = temp2;   
            if (temp < temp2)
            {
                temp2 = temp;
                nearZero = data[i];
            }


        }

        c.println ("The number closest to zero is: " + nearZero);

        // Place your program here.  'c' is the output console
    } // main method
} // Ass_1_B_3 class
-1
public class Main    
{
    public static void main(String[] args)
    {   
        int[] numbers = {6,5,10,1,3,4,2,14,11,12};

        for(int i =0; i<numbers.length; i++)
        {
            sum(numbers, i, numbers[i], 12, String.valueOf(numbers[i]));
        }
    }

    static void sum(int[] arr, int i, int sum, int target, String s)
    {

        int flag = 0;

        for(int j = i+1; j<arr.length; j++)
        {

            if(arr[i] == target && flag==0)
            {
                System.out.println(String.valueOf(arr[i]));
                flag =1;

            }
            else if(sum+arr[j] == target)
            { 
                System.out.println(s+" "+String.valueOf(arr[j]));

            }
            else
            {
                sum(arr, j, sum+arr[j], target, s+" "+String.valueOf(arr[j]));
            }
        }        
    }
}
1
  • get array and calculate the target value in java
    – Rivean
    Feb 3, 2018 at 2:41
-2

Kotlin - TreeSet lower method returns the greatest element in this set strictly less than the given element, or null if there is no such element.

import java.util.*

fun printLowest(number: Int) {
    val numbers = listOf(100, 90, 50, -100, -200, 532, 6584, -945)
    val lower = TreeSet(numbers).lower(number)
    println(lower)
}

printLowest(100) // Prints 90
0
-8

Here is something that i did...

import javax.swing.JOptionPane;

public class NearestNumber {

public static void main(String[] arg)
{
    int[] array={100,-3420,3040,400433,500,-100,-200,532,6584,-945};

    String myNumberString =JOptionPane.showInputDialog(null,"Enter the number to test:");
    int myNumber = Integer.parseInt(myNumberString);

    int nearestNumber = findNearestNumber(array,myNumber);

    JOptionPane.showMessageDialog(null,"The nearest number is "+nearestNumber);
}

public static int findNearestNumber(int[] array,int myNumber)
{

    int min=0,max=0,nearestNumber;

    for(int i=0;i<array.length;i++)
    {
        if(array[i]<myNumber)
        {
            if(min==0)
            {
                min=array[i];
            }
            else if(array[i]>min)
            {
                min=array[i];
            }
        }
        else if(array[i]>myNumber)
        {
            if(max==0)
            {
                max=array[i];
            }
            else if(array[i]<max)
            {
                max=array[i];
            }
        }
        else
        {
            return array[i];
        }
    }

    if(Math.abs(myNumber-min)<Math.abs(myNumber-max))
    {
        nearestNumber=min;
    }
    else
    {
        nearestNumber=max;
    }

    return nearestNumber;
}

}

1
  • this looks like a rocket science! :)
    – Diablo
    May 19, 2022 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.