Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get closest value to a number in array

Tags:

java

arrays

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?

like image 476
Get Off My Lawn Avatar asked Nov 10 '12 02:11

Get Off My Lawn


People also ask

How do I find the closest number in an array in C?

So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.

How do I find the nearest number in an array in Excel?

Find the closest or nearest number with array formulaSelect a blank cell, and enter below formula, and press the Ctrl + Shift + Enter keys together. Note: In this array formula of {=INDEX(B3:B22,MATCH(MIN(ABS(B3:B22-E2)),ABS(B3:B22-E2),0))}, B3:B22 is the range that you want to find the specific value.

How do you find the closest value to zero from an array with positive and negative numbers in Java?

In the Array if the values are like 1 and -1 the closest should be the positive value. technically 1 and -1 both are equally close to 0. by the difference of 1. In this case, add another if statement to check if it's positive or negative.


1 Answers

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.

like image 68
Chris Hayes Avatar answered Oct 02 '22 12:10

Chris Hayes