English 中文(简体)
阵列中最接近的价值
原标题:finding closest value in an array
int[] array = new int[5]{5,7,8,15,20};

int TargetNumber = 13;

就目标数目而言,我想找到一个阵列中最接近的数目。 例如,当目标数目为13个时,上述阵列中最接近的目标数是15个。 我如何在C#中以方案方式做到这一点?

最佳回答

EDIT: 调整了以下询问,以改用long 算术,以避免超支问题。

我可能使用MoreLINQMinBy。 方法:

var nearest = array.MinBy(x => Math.Abs((long) x - targetNumber));

页: 1 公正使用:

var nearest = array.OrderBy(x => Math.Abs((long) x - targetNumber)).First();

......但是,这将把全部收集归为一类,你们确实不需要。 它对一个小型阵列来说没有多大变化,这当然是......,与你所描述的“实际:根据某些功能找到最低价值要素”相比,它并不感到相当正确。

请注意,如果阵列空,这两人都将失败,因此,你应首先检查。

问题回答

如果你重新使用。 准则3.5或以上净额可帮助您:

var closest = array.OrderBy(v => Math.Abs((long)v - targetNumber)).First();

或者,你可以撰写你自己的推广方法:

public static int ClosestTo(this IEnumerable<int> collection, int target)
{
    // NB Method will return int.MaxValue for a sequence containing no elements.
    // Apply any defensive coding here as necessary.
    var closest = int.MaxValue;
    var minDifference = int.MaxValue;
    foreach (var element in collection)
    {
        var difference = Math.Abs((long)element - target);
        if (minDifference > difference)
        {
            minDifference = (int)difference;
            closest = element;
        }
    }

    return closest;
}

可使用:

var closest = array.ClosestTo(targetNumber);

Jon和Rich都对做了大量回答。 MinBy and Closest To 。 但是,如果你打算找到一个单一要素,我就永远不会建议使用<条码>OrderBy。 它对此类任务效率太低。 它只是工作的一个错误工具。

在此,一种比MinBy低效的技术已经列入“NET”框架,但低于MinBy:Aggregate

var nearest = array.Aggregate((current, next) => Math.Abs((long)current - targetNumber) < Math.Abs((long)next - targetNumber) ? current : next);

正如我说过的,不是作为Joon的主人,而是可行的。

我的计算机性能:

  1. For(each) Loops = fastest
  2. Aggregate = 2.5x slower than loops
  3. MinBy = 3.5x slower than loops
  4. OrderBy = 12x slower than loops

我几年前在Math发现这种真正的性做法。 NET Numerics https://mathics.mathdotnet.com/ 后者与阵列中的平流层合作。 它对准备进行干涉,并努力达到2.0Net:

public static int LeftSegmentIndex(double[] array, double t)
{
    int index = Array.BinarySearch(array, t);
    if (index < 0)
    {
        index = ~index - 1;
    }
    return Math.Min(Math.Max(index, 0), array.Length - 2);
}

如果你需要找到最接近平均水平的价值的话

very open style

public static double Miidi(double[] list)
{
    bool isEmpty = !list.Any();
    if (isEmpty)
    {
        return 0;
    }
    else
    {
        double avg = list.Average();
        double closest = 100;
        double shortest = 100;
        {
            for ( int i = 0; i < list.Length; i++)
            {
                double lgth = list[i] - avg;
                if (lgth < 0)
                {
                    lgth = lgth - (2 * lgth);
                }
                else
                    lgth = list[i] - avg;

                if (lgth < shortest)
                {
                    shortest = lgth;
                    closest = list[i];
                }
            }
        }

        return closest;
    }
}

业绩明智的习俗法典将更加有用。

public static int FindNearest(int targetNumber, IEnumerable<int> collection) {
    var results = collection.ToArray();
    int nearestValue;
    if (results.Any(ab => ab == targetNumber))
        nearestValue = results.FirstOrDefault(i => i == targetNumber);
    else{
        int greaterThanTarget = 0;
        int lessThanTarget = 0;
        if (results.Any(ab => ab > targetNumber)) {
            greaterThanTarget = results.Where(i => i > targetNumber).Min();
        }
        if (results.Any(ab => ab < targetNumber)) {
            lessThanTarget = results.Where(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;
        }
    }
    return nearestValue;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签