Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to returns the nearest element of array to an integer

I want to make a function that gives an array returns the nearest element to a number.

here is some examples:

int[] arr = new int[] {12, 48, 50, 100};
my_function(1, arr); // returns 12.
my_function(40, arr); // returns 48.
my_function(49, arr); // returns 50; in two element with equal distance, returns greater number
my_function(70, arr); // returns 50.
my_function(10005, arr); // returns 100.

Sorry, I have no idea about how to write this function.


2 Answers

private int GetNearest(int[] array,int number)
{
    return array.OrderBy(x => Math.Abs((long)x - number)).FirstOrDefault();
}

If you want to be sure that the larger number is before smaller number when the absolute difference is the same, add .ThenByDescending(a => a) after OrderBy(x => Math.Abs((long)x - number))

private int GetNearest(int[] array,int number)
{
    return array.OrderBy(x => Math.Abs((long)x - number)).ThenByDescending(a => a).FirstOrDefault();
}
like image 69
Farhad Zamani Avatar answered May 04 '26 07:05

Farhad Zamani


This is a solution without using System.Linq and with O(n) complexity. You just go through array in loop and find a number with minimal difference, abs <= diff condition allows you to return the latest number (50 for 49 instead of 48) in sorted array. If difference equals 0, it means that you find the exact number

var arr = new[] { 12, 48, 50, 100 };

int nearest = GetNearest(1, arr);
nearest = GetNearest(40, arr);
nearest = GetNearest(49, arr);
nearest = GetNearest(70, arr);
nearest = GetNearest(1005, arr);

int GetNearest(int number, int[] array)
{
    int diff = int.MaxValue;
    int result = 0;
    foreach (var item in array)
    {
        var abs = Math.Abs(item - number);
        if (abs == 0)
        {
            result = item;
            break;
        }

        if (abs <= diff)
        {
            diff = abs;
            result = item;
        }
    }

    return result;
}
like image 29
Pavel Anikhouski Avatar answered May 04 '26 05:05

Pavel Anikhouski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!