简体   繁体   中英

Nearest value from user input in an array C#

so in my application , I read some files into it and ask the user for a number , in these files there a lot of numbers and I am trying to find the nearest value when the number they enter is not in the file. So far I have as following

 static int nearest(int close_num, int[] a)
    {
        foreach (int bob in a)
        {
            if ((close_num -= bob) <= 0)
                return bob;
        }
        return -1;
    }


 Console.WriteLine("Enter a number to find out if is in the selected Net File:  ");
        int i3 = Convert.ToInt32(Console.ReadLine());
        bool checker = false;
        //Single nearest = 0;
        //linear search#1
        for (int i = 0; i < a.Length; i++)//looping through array
        {
            if(a[i] == i3)//checking to see the value is found in the array
            {
                Console.WriteLine("Value found and the position of it in the descending value of the selected Net File is: " + a[i]);
                checker = true;
            }              
            else 
            {
                int found = nearest(i3,a);
                Console.WriteLine("Cannot find this number in the Net File however here the closest number to that: " + found );
                //Console.WriteLine("Cannot find this number in the Net File however here the closest number to that : " + nearest);
            }
        }

When a value that is in the file is entered the output is fine , but when it comes to the nearest value I cannot figure a way. I can't use this such as BinarySearchArray for this. a = the array whilst i3 is the value the user has entered. Would a binary search algorithm just be simpler for this? Any help would be appreciated.

Well, first we should define , what is nearest . Assuming that,

int nearest for given int number is the item of int[] a such that Math.Abs(nearest - number) is the smallest possible value

we can put it as

static int nearest(int number, int[] a)
{
    long diff = -1;
    int result = 0;

    foreach (int item in a)
    {
        // actual = Math.Abs((long)item - number);
        long actual = (long)item - number;

        if (actual < 0) 
            actual = -actual;

        // if item is the very first value or better than result 
        if (diff < 0 || actual < diff) {
            result = item;
            diff = actual;
        }            
    }

    return result;
}

The only tricky part is long for diff : it may appear that item - number exceeds int range (and will either have IntegerOverflow exceprion thrown or *invalid answer), eg

 int[] a = new int[] {int.MaxValue, int.MaxValue - 1};

 Console.Write(nearest(int.MinValue, a));

Note, that expected result is 2147483646 , not 2147483647

You need to make a pass over all the elements of the array, comparing each one in turn to find the smallest difference. At the same time, keep a note of the current nearest value.

There are many ways to do this; here's a fairly simple one:

static int nearest(int close_num, int[] a)
{
    int result = -1;
    long smallestDelta = long.MaxValue;

    foreach (int bob in a)
    {
        long delta = (bob > close_num) ? (bob - close_num) : (close_num - bob);

        if (delta < smallestDelta)
        {
            smallestDelta = delta;
            result = bob;
        }
    }

    return result;
}

Note that delta is calculated so that it is the absolute value of the difference.

LINQ呢?

var nearestNumber = a.OrderBy(x => Math.Abs(x - i3)).First();

Just iterate through massive and find the minimal delta between close_num and array members

static int nearest(int close_num, int[] a)
{ 
     // initialize as big number, 1000 just an example        
    int min_delta=1000;
    int result=-1;
    foreach (int bob in a)
    {
        if (Math.Abs(bob-close_num) <= min_delta)
           {
              min_delta = bob-close_num;
              result = bob;
           }
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM