C# – 从十进制数组中查找最接近的索引
发布时间:2020-12-15 08:44:42 所属栏目:百科 来源:网络整理
导读:decimal[] array = new decimal[5]{80.23,60.20,88.01,77.00,20.45};decimal TargetNumber = 70.40; 这里,最近的值是77.00,如何找到最接近的十进制数组的索引? 注意:它应该保持与我需要的最接近值的精确索引相同的顺序.在这里,指数比价值重要 解决方法 关
decimal[] array = new decimal[5]{80.23,60.20,88.01,77.00,20.45}; decimal TargetNumber = 70.40; 这里,最近的值是77.00,如何找到最接近的十进制数组的索引? 注意:它应该保持与我需要的最接近值的精确索引相同的顺序.在这里,指数比价值重要 解决方法
关于使用LINQ做很多事情的一个好处是,如果找到完全匹配,你可以提前停止检查. minIndex保存索引,如果数组为空,则保持-1.
decimal minDistance = 0; //0 is fine here it is never read,it is just to make the compiler happy. int minIndex = -1; for(int i = 0; i < array.Length; i++) { var distance = Math.Abs(TargetNumber - array[i]); if(minIndex == -1 || distance < minDistance) { minDistance = distance; minIndex = i; //Optional,stop testing if we find a exact match. if(minDistance == 0) break; } } 为了好玩,我制作了一个完全通用的版本,它要求你传入一个委托来计算距离因子,它还有一个可选参数来定义停止检查更多结果所需的“最小距离”. using System; using System.Collections.Generic; public class Program { public static void Main() { decimal[] array = new decimal[5]{80.23M,80.40M,80.80M,80.00M,20.45M}; decimal TargetNumber = 70.40M; var result = FindClosestIndex(TargetNumber,array,(target,element) => Math.Abs(target - element)); //Optionally add in a "(distance) => distance == 0" at the end to enable early termination. Console.WriteLine(result); } public static int FindClosestIndex<T,U>(T target,IEnumerable<T> elements,Func<T,T,U> distanceCalculator,Func<U,bool> earlyTermination = null) where U : IComparable<U> { U minDistance = default(U); int minIndex = -1; using(var enumerator = elements.GetEnumerator()) for(int i = 0; enumerator.MoveNext(); i++) { var distance = distanceCalculator(enumerator.Current,target); if(minIndex == -1 || minDistance.CompareTo(distance) > 0) { minDistance = distance; minIndex = i; } if(earlyTermination != null && earlyTermination(minDistance)) break; } return minIndex; } } Runnable example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 使用ActiveResource在Rails中使用非REST
- 【熟悉引擎第二步】Cocos2d-x 3.x中使用物理引擎创建物理元
- c# – EF 6 – 一对多映射始终为空
- Flex3学习轨迹:让Alert对话框不可拖动
- Office 365 - For security reasons DTD is prohibited in
- 闪光 – 行星的引力
- oracle – ORA-28040:没有匹配的身份验证协议异常
- 猴子在有限的范围内修补内置的ruby类
- ruby-on-rails – Rails 3帮助方法在模型中可用
- c# – 更改DataGrid(WPF)行中的单元格正在更改下面行中的单