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