This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
How do I get approximations in arrays?
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;
Copy the code
I want to test an int on this array and return the number closest to an int.
For example, if I use the number 490 and I get the fourth term from the number 500, what’s the best way to do something like that?
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];
Copy the code
Is there a good way to do it?
Answer a
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];
Copy the code
Always consider initializing the min/ Max function with the first element. Using methods such as integer.max_value or integer.min_value to get the answer is a primitive method; If you change the data type later, it won’t work (oops, MAX_LONG and MAX_INT are very different!). Or, if you want to write a generic min/ Max method for any data type.
Answer two
In Java8, you can write like this
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"));
Copy the code
You can use collections instead of arrays (collections have more functionality).
Answer three
A statement block to initialize and set the closest match. Also, if no closest match is found, -1 (an empty array) is returned.
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;
}
Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/1…