从一个给定清单检测至少3顺序编号的顺序 [英] Detecting sequence of at least 3 sequential numbers from a given list

查看:183
本文介绍了从一个给定清单检测至少3顺序编号的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有号码列表例如21,4,7,9,12,22,17,8,2,20,23

I have a list of numbers e.g. 21,4,7,9,12,22,17,8,2,20,23

我希望能够挑选出连续的数字序列(最小长度为3项),因此从上面的例子中这将是7,8,9和20,21,22,23。

I want to be able to pick out sequences of sequential numbers (minimum 3 items in length), so from the example above it would be 7,8,9 and 20,21,22,23.

我曾与一些发挥各地丑陋的庞大的功能,但我想知道是否有一个整洁的LINQ十岁上下的方式来做到这一点。

I have played around with a few ugly sprawling functions but I am wondering if there is a neat LINQ-ish way to do it.

有什么建议?

更新:

非常感谢所有的答复,大大appriciated。林目前我跟他们都可以看到这将最好的融入到我们的项目中发挥作用。

Many thanks for all the responses, much appriciated. Im am currently having a play with them all to see which would best integrate into our project.

推荐答案

全碟/ Timwi的解决方案是要走的路。

Jon Skeet's / Timwi's solutions are the way to go.

为了好玩,这里是一个LINQ查询,没有工作(的非常的低效率):

For fun, here's a LINQ query that does the job (very inefficiently):

var sequences = input.Distinct()
                     .GroupBy(num => Enumerable.Range(num, int.MaxValue - num + 1)
                                               .TakeWhile(input.Contains)
                                               .Last())  //use the last member of the consecutive sequence as the key
                     .Where(seq => seq.Count() >= 3)
                     .Select(seq => seq.OrderBy(num => num)); // not necessary unless ordering is desirable inside each sequence.



查询的性能可以通过加载输入到的HashSet <略有改善/ code>(改善包含),但是这仍然无法产生一个解决方案,任何接近高效。

The query's performance can be improved slightly by loading the input into a HashSet (to improve Contains), but that will still not produce a solution that is anywhere close to efficient.

我所知道的唯一的错误是算术溢出的可能性,如果序列中包含负数的大幅度 (我们不能代表计数参数范围)。这将是容易定制的解决静态的IEnumerable< INT>要(这INT开始,诠释完)扩展法。如果任何人都可以想躲着溢出的任何其他简单的技术,请让我知道

The only bug I am aware of is the possibility of an arithmetic overflow if the sequence contains negative numbers of large magnitude (we cannot represent the count parameter for Range). This would be easy to fix with a custom static IEnumerable<int> To(this int start, int end) extension-method. If anyone can think of any other simple technique of dodging the overflow, please let me know.

编辑:
这里有一个稍微更详细的(但同样效率不高) 。变型而不溢出问题。

Here's a slightly more verbose (but equally inefficient) variant without the overflow issue.

var sequences = input.GroupBy(num => input.Where(candidate => candidate >= num)
                                          .OrderBy(candidate => candidate)
                                          .TakeWhile((candidate, index) => candidate == num + index)
                                          .Last())
                     .Where(seq => seq.Count() >= 3)
                     .Select(seq => seq.OrderBy(num => num));

这篇关于从一个给定清单检测至少3顺序编号的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆