If I have an array like this:
var array = [1, 3, 4, 5, 9, 10];
And I have a value like this:
var value = 8;
I want to get this result:
var result = getClosestValues(array, value); // [5, 9]
What's the correct/preferred way to do this in javascript? It seems like this is probably a formal algorithm somewhere. Maybe like this:
var getClosestValues = function(array, value) {
var low, high = 0, value;
for (var i = 0; i < array.length; i++) {
if (low <= value && low < array[i])
low = array[i];
if (high == value && high < array[i])
high = array[i];
};
return [low, high];
}
Thanks!
A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference. An efficient solution is to use Binary Search.
Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .
Start from the first element and search for the crossover point (The point before which elements are smaller than or equal to X and after which elements are greater). This step takes O(n) time. Once we find the crossover point, we can compare elements on both sides of crossover point to print k closest elements.
The greatest integer function is also known as the step function. It rounds up the number to the nearest integer less than or equal to the given number.
If the array is sorted and large, use a binary chop to find the nearest elements:
var getClosestValues = function(a, x) {
var lo = -1, hi = a.length;
while (hi - lo > 1) {
var mid = Math.round((lo + hi)/2);
if (a[mid] <= x) {
lo = mid;
} else {
hi = mid;
}
}
if (a[lo] == x) hi = lo;
return [a[lo], a[hi]];
}
Otherwise, just scan from one end to the other, keeping track of the nearest values above and below the target. For this algorithm, your version is broken, unfortunately. Here's another version:
var getClosestValues = function(a, x) {
var lo, hi;
for (var i = a.length; i--;) {
if (a[i] <= x && (lo === undefined || lo < a[i])) lo = a[i];
if (a[i] >= x && (hi === undefined || hi > a[i])) hi = a[i];
};
return [lo, hi];
}
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