c# – 以6个为一组比较arrary中的每个数字
发布时间:2020-12-15 21:43:37 所属栏目:百科 来源:网络整理
导读:你好伙计们我??正在做一点自我学习,我遇到的问题似乎已经困扰了我暂时不知道我有人在这里确定已经遇到了类似于此的事情.我有一个1-10的数组列表 public Listint ValueArrays = new Listint { 1,2,3,4,5,6,7,8,9,10 }; 即时通讯试图获得6个数字组的总和,但我
你好伙计们我??正在做一点自我学习,我遇到的问题似乎已经困扰了我暂时不知道我有人在这里确定已经遇到了类似于此的事情.我有一个1-10的数组列表
public List<int> ValueArrays = new List<int> { 1,2,3,4,5,6,7,8,9,10 }; 即时通讯试图获得6个数字组的总和,但我只是卡住了. [1,6] [1,7] [1,8] etc... 我写了一些代码,但我只是在这里磕磕绊绊. private void runbtn_Click(object sender,EventArgs e) { int thisTotal; //Object ListOfNumbersToCompareTo = new Object[]; List<int> fiveEl = new List<int> { }; //= ValueArrays.GetRange(1,5);//target a group of 5 List<int> test2 = new List<int> { }; //test2.AddRange(fiveEl); //thisTotal = SumRange(fiveEl); int groupSize = 5; for (int i = 0; i < ValueArrays.Count; i++) { fiveEl=ValueArrays.GetRange(i+1,5); currentNum = ValueArrays[i]; fiveEl.Add(currentNum); for (int x = 0; x < 1; x++) { thisTotal = SumRange(fiveEl); //fiveEl = ValueArrays.GetRange(x,groupSize); //fiveEl.Add(currentNum); //fiveEl.RemoveRange(x,groupSize); ; } } } 有人可以给我一个代码片段或指向我正确的方向吗? 解决方法
就个人而言,我会这样写:
var values = new List<int> { 1,10 }; var groupsOfSix = values.Subsequences().Where(s => s.Count() == 6); 当然,你可以在这样生成的每个子序列上使用.Sum(). 这使用了我前一段时间写的扩展方法,它生成IEnumerable< T>的所有子序列.这种解决方案不是最快速的解决方案,但是通过它可以使代码易于阅读并且显然是正确的,并且在仅10个元素的输入列表上,它的速度足够快. 这是子序列函数: /// <summary> /// Returns all subsequences of the input <see cref="IEnumerable<T>"/>. /// </summary> /// <param name="source">The sequence of items to generate subsequences of.</param> /// <returns>A collection containing all subsequences of the input <see cref="IEnumerable<T>"/>.</returns> public static IEnumerable<IEnumerable<T>> Subsequences<T>(this IEnumerable<T> source) { if (source == null) throw new ArgumentNullException("source"); // Ensure that the source IEnumerable is evaluated only once return subsequences(source.ToArray()); } private static IEnumerable<IEnumerable<T>> subsequences<T>(IEnumerable<T> source) { if (source.Any()) { foreach (var comb in subsequences(source.Skip(1))) { yield return comb; yield return source.Take(1).Concat(comb); } } else { yield return Enumerable.Empty<T>(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |