Compare value with array and get closest value to it

青春壹個敷衍的年華 提交于 2019-12-04 14:53:31

You can do this with some simple mathematics and there are different approaches.

LINQ

Double searchValue = ...;

Double nearest = w.Select(p => new { Value = p, Difference = Math.Abs(p - searchValue) })
                  .OrderBy(p => p.Difference)
                  .First().Value;

Manually

Double[] w = { 1000, 2000, 3000, 4000, 5000 };

Double searchValue = 3001;
Double currentNearest = w[0];
Double currentDifference = Math.Abs(currentNearest - searchValue);

for (int i = 1; i < w.Length; i++)
{
    Double diff = Math.Abs(w[i] - searchValue);
    if (diff < currentDifference)
    {
        currentDifference = diff;
        currentNearest = w[i];
    }
}
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var minimumValueFromArray = w.Min();

produces

1000, as expected, cause we execute Enumerable.Min.

The same is for Enumerable.Max, to figure out the max value:

Double[] w = { 1000, 2000, 3000, 4000, 5000 };
var maximumValueFromArray = w.Max();

Considering that you're comparing with the double.MinValue and double.MaxValue, I would assume that you want just pick the smallest and biggest value from array.

If this is not what you're searching for, please clarify.

based on your code, you can achieve this in a very easy way

    Double[] w = { 1000, 2000, 3000, 4000, 5000 }; // it has to be sorted

    double search = 3001;
    double lowerClosest = 0;
    double upperClosest = 0;


        for (int i = 1; i < w.Length; i++)
        {
            if (w[i] > search)
            {
                upperClosest = w[i];
                break; // interrupts your foreach
            }

        }
        for (int i = w.Length-1; i >=0; i--)
        {
            if (w[i] <= search)
            {
                lowerClosest = w[i];
                break; // interrupts your foreach
            }

        }

    Console.WriteLine(" lowerClosest:{0}", lowerClosest);
    Console.WriteLine(" upperClosest:{0}", upperClosest);
    if (upperClosest - search > search - lowerClosest)
        Console.WriteLine(" Closest:{0}", lowerClosest);
    else
        Console.WriteLine(" Closest:{0}", upperClosest);

    Console.ReadLine();

depending on the position of your search value this will be less than O(n)

                Performance wise custom code will be more use full. 

                List<int> results;
                int targetNumber = 0;
                int nearestValue=0;
                if (results.Any(ab => ab == targetNumber ))
                {
                    nearestValue= results.FirstOrDefault<int>(i => i == targetNumber );
                }
                else
                {
                    int greaterThanTarget = 0;
                    int lessThanTarget = 0;
                    if (results.Any(ab => ab > targetNumber ))
                    {
                        greaterThanTarget = results.Where<int>(i => i > targetNumber ).Min();
                    }
                    if (results.Any(ab => ab < targetNumber ))
                    {
                        lessThanTarget = results.Where<int>(i => i < targetNumber ).Max();
                    }

                    if (lessThanTarget == 0 )
                    {
                        nearestValue= greaterThanTarget;
                    }
                    else if (greaterThanTarget == 0)
                    {
                        nearestValue= lessThanTarget;
                    }
                    else if (targetNumber - lessThanTarget < greaterThanTarget - targetNumber )
                    {
                        nearestValue= lessThanTarget;
                    }
                    else
                    {
                            nearestValue= greaterThanTarget;
                    }
                }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!