Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formal way of getting closest values in array in Javascript, given a value and a sorted array?

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!

like image 245
Lance Avatar asked Dec 13 '10 16:12

Lance


People also ask

How do I find the nearest number in a sorted array?

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.

How do I find the closest number in JavaScript?

Therefore, to find out the closest number we just return the index of the found minimum in the given array indexArr. indexOf(min) .

How do I find the closest value?

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.

Which function returns the higher value to the closest integer?

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.


1 Answers

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];
}
like image 196
Marcelo Cantos Avatar answered Sep 21 '22 12:09

Marcelo Cantos