# get closest value to a number in array

by Get Off My Lawn   Last Updated January 14, 2018 12:26 PM

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?

Tags :

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.

Don
November 10, 2012 02:47 AM

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

irrelephant
November 10, 2012 02:48 AM

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

Chris Hayes
November 10, 2012 02:52 AM

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;
}
``````

}

ntstha
November 10, 2012 10:06 AM

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
``````
February 19, 2016 03:09 AM

``````public int nearnum(int myNumber,int[] numbers)
{
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;
}
}
return numbers[idx];
}
``````
saran saran
February 21, 2016 05:19 AM

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;
}
``````
farid_z
December 29, 2016 18:22 PM

``````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;
}
``````
April 05, 2017 10:44 AM

With Java 8 Stream API:

``````List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());
int n = 490;
int closestToN = list.stream().min(Comparator.comparingInt(i -> Math.abs(i - n))).get();
``````

Originally, you might want to use a List instead of array, thus you can get additional flexibility in computations.

Oleksandr
January 07, 2018 12:52 PM