+ 1

Method for finding the closest to a value from an array?

Say: int val is a number and i need to search through an array, int arr[] for the value closest to val. but also depending on another value, int c ,which determines closest, second closest, third closest, etc. to val How can i write code for this?

24th Apr 2019, 4:30 PM
Jamie Charles
2 Réponses
+ 2
Example: Array: 12,34,1,5,3 val = 7 |7-12| = 5 |7-34| = 27 |7-1| = 6 |7-5| = 2 |7- 3| = 4 --> 5 is closest to 7 abs of a value: Math.abs() Use a for loop to calc Math.abs(val - arr[i]) Maybe you should store the abs values into another array. Only the closest: int min = (int)Math.abs(val - arr[0]); int c = arr[0]; for(int i = 1; i < arr.length; i++){ if(min > Math.abs(val - arr[i]){ min = (int)Math.abs(val - arr[i]); c = arr[i]; } }
24th Apr 2019, 11:10 PM
Denise Roßberg
Denise Roßberg - avatar
0
if you are more advanced: add numbers to Integer[] array arr write your own Comparator<Integer> where compare abs(v-n1) - abs(v-n2) sort array with your comparator comp Arrays.sort(arr, comp) if v=4 for numbers {7, 8, 2, 3, 6, 4, 5, 9, 1} you get [4, 3, 5, 2, 6, 7, 1, 8, 9] where 4 is 1 closest to 4 3,5 are 2 closest 2,6 are 3 closest ...
25th Apr 2019, 8:31 AM
zemiak