Hello.

There is such a task. Suppose there is a number 150. There is an array with numbers [145, 5, 7, 148, 161,190,153, etc.].

How can you find out the nearest smaller and nearest larger number? (In this example, it should be the numbers 148 and 153.) I stuck with h.g. with this question. Thank you in advance.

    3 answers 3

    How can you find out the nearest smaller and nearest larger number?

    Go through the array, comparing each number, and updating one of the closest ones, if you need to update it, no magic here

    var closestLeft, closestRight, data = [145, 5, 7, 148, 161, 190, 153], number = 150, current; for (var i = 0; i < data.length; i++) { current = data[i]; if (current < number && (typeof closestLeft === 'undefined' || closestLeft < current)) { closestLeft = current; } else if (current > number && (typeof closestRight === 'undefined' || closestRight > current)) { closestRight = current; } } 

    jquery

    awesome link

    • Thank. I wandered off at that steppe - leonoff

    I will not write the code, I will show the algorithm (perhaps not the most optimal, I will not vouch for it)

    1. Get two variables, one of which (let's call it minApproach) will store the closest number that is less than the specified one, the second (let's call it maxApproach) is the closest one that is greater than the specified
    2. Assign the corresponding values ​​to these variables. for minApproach, the value of the first element that is less than the specified number. For maxApproach, the first value that is greater than the specified one.
    3. If one of the two values ​​was not found at the previous step (in other words, if the specified value is the minimum or maximum of the array), then it does not make sense to look for one of the near values ​​(minApproach or maxApproach)
    4. Run in a loop over all elements of the array and compare each with the two variables above.
    5. if the next element of the array is greater than the specified number (150) and at the same time less than maxApproach, then write its value to maxApproach. In the same way, we compare with minApproach with the only difference that the element must be less than the specified, but more than maxApproach

    Actually, everything

    • Thank. The problem was just in the construction of the algorithm. - leonoff

    Here's another solution js (babel) as you can find out the nearest smaller and nearest larger number in the array.

     const data = [145, 5, 7, 148, 161, 190, 153]; const number = 150; const closestRight = Math.min(...data.filter(v => v > number)); const closestLeft = Math.max(...data.filter(v => v < number));