gpt4 book ai didi

c# - 列表中满足条件的所有元素的最小值

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:36 25 4
gpt4 key购买 nike

我有一个二维点类如下:

class Point
{
public int id_;
public float x_, y_;

public Point(int i, float x, float y)
{
id_ = i;
x_ = x;
y_ = y;
}

public float Distance(Point otherPoint)
{
return (float)Math.Sqrt(Math.Pow(x_ - otherPoint.x_, 2) + Math.Pow(y_ - otherPoint.y_, 2));
}
}

在我的主要代码中,我列出了这些要点。我提出了一个新观点。如果满足最小阈值标准,我想在我的列表中找到距离新点最短的点。

我最初写的很简单,有一个 minValue(初始化为 1e6)和一个 minID,遍历列表以找到最小值。在遍历之外,我检查了这个最小值是否小于阈值。那行得通。

但我想看看是否有更好/更简洁的方法来实现它,最后我得到了这个:

var list = new List<Point>();
list.Add(new Point(0, 10.0f, 1.0f));
list.Add(new Point(1, 1.0f, 0.0f));
list.Add(new Point(2, 0.0f, 0.0f));

var p = new Point(3, 0.6f, 0.0f);
var subList = list.Select((item, index) => new { item, index })
.Where(x => (x.item.distance(p) <= 1.0))
.Select(x => x.item).ToList();

Point minPoint = subList[Enumerable.Range(0, subList.Count).Aggregate((a, b) => (subList[a].Distance(p) < subList[b].Distance(p) ? a : b))];
Console.WriteLine(minPoint.id_);

有更好的方法吗?

最佳答案

我宁愿使用以下方法,它进行 O(N) 距离计算和 O(N) 比较:

var closest = list.Select(item => new { item, distance = item.Distance(p) })
.Aggregate((a, b) => a.distance <= b.distance ? a : b);
var closestPt = closest.distance <= 1.0 ? closest.item : null;

关于c# - 列表中满足条件的所有元素的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com