从给定列表中检测至少 3 个连续数字的序列
我有一个数字列表,例如 21,4,7,9,12,22,17,8,2,20,23
我希望能够挑选出连续数字的序列(长度至少为 3 个项目),所以从上面的例子是 7,8,9 和 20,21,22,23。
我尝试过一些丑陋的庞大函数,但我想知道是否有一种简洁的 LINQ 风格的方法来做到这一点。
有什么建议吗?
更新:
非常感谢您的所有回复,非常感谢。我目前正在与他们一起玩,看看哪一个最适合融入我们的项目。
I have a list of numbers e.g. 21,4,7,9,12,22,17,8,2,20,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.
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.
Any suggestions?
UPDATE:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
我突然意识到你应该做的第一件事就是订购清单。然后只需遍历它,记住当前序列的长度并检测它何时结束即可。老实说,我怀疑简单的 foreach 循环将是最简单的方法 - 我无法立即想到任何非常简洁的类似 LINQ 的方法。如果您确实愿意,您当然可以在迭代器块中执行此操作,但请记住,对列表进行排序意味着无论如何您都有相当的“前期”成本。所以我的解决方案看起来像这样:
编辑:好的,我只是想到了一种更类似于 LINQ 的做事方式。我现在没有时间完全实现它,但是:
SelectWithPrevious
(可能更好地命名为SelectConsecutive
)来获取连续的元素SelectWithPrevious
在结果上获取两个起点之间序列的长度(从前一个索引中减去一个索引)我怀疑你需要在有序序列上连接
int.MinValue
,以保证最终项目被正确使用。编辑:好的,我已经实现了这个。这是我能想到的最 LINQest 方法...我使用 null 值作为“哨兵”值来强制开始和结束序列 - 有关更多详细信息,请参阅注释。
总的来说,我不会推荐这个解决方案。很难让你清醒过来,尽管我相当有信心它是正确的,但我花了一段时间思考可能存在的相差一错误等。这是一次有趣的探索你可以做什么的旅程使用 LINQ...以及您可能不应该做的事情。
哦,请注意,我已将“最小长度 3”部分推送给调用者 - 当您有这样的元组序列时,单独过滤掉它会更干净,IMO。
It strikes me that the first thing you should do is order the list. Then it's just a matter of walking through it, remembering the length of your current sequence and detecting when it's ended. To be honest, I suspect that a simple foreach loop is going to be the simplest way of doing that - I can't immediately think of any wonderfully neat LINQ-like ways of doing it. You could certainly do it in an iterator block if you really wanted to, but bear in mind that ordering the list to start with means you've got a reasonably "up-front" cost anyway. So my solution would look something like this:
EDIT: Okay, I've just thought of a rather more LINQ-ish way of doing things. I don't have the time to fully implement it now, but:
SelectWithPrevious
(probably better namedSelectConsecutive
) to get consecutive pairs of elementsSelectWithPrevious
on the result to get the length of the sequence between two starting points (subtract one index from the previous)I suspect you need to concat
int.MinValue
on the ordered sequence, to guarantee the final item is used properly.EDIT: Okay, I've implemented this. It's about the LINQiest way I can think of to do this... I used null values as "sentinel" values to force start and end sequences - see comments for more details.
Overall, I wouldn't recommend this solution. It's hard to get your head round, and although I'm reasonably confident it's correct, it took me a while thinking of possible off-by-one errors etc. It's an interesting voyage into what you can do with LINQ... and also what you probably shouldn't.
Oh, and note that I've pushed the "minimum length of 3" part up to the caller - when you have a sequence of tuples like this, it's cleaner to filter it out separately, IMO.
Jon Skeet / Timwi 的解决方案是正确的选择。
为了好玩,这里有一个 LINQ 查询来完成这项工作(非常效率低下):
通过将输入加载到
HashSet
中,可以稍微提高查询的性能(以提高包含
),但这仍然不会产生一个接近高效的解决方案。我知道的唯一错误是,如果序列包含
大量的负数,则可能会出现算术溢出(我们无法表示Range<的
count
参数) /代码>)。使用自定义static IEnumerable可以很容易地解决这个问题。 To(this int start, int end)
扩展方法。如果有人能想到任何其他简单的避免溢出的技术,请告诉我。编辑:
这是一个稍微详细(但同样低效)的变体,没有溢出问题。
Jon Skeet's / Timwi's solutions are the way to go.
For fun, here's a LINQ query that does the job (very inefficiently):
The query's performance can be improved slightly by loading the input into a
HashSet
(to improveContains
), but that will still not produce a solution that is anywhere close to efficient.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 thecount
parameter forRange
). This would be easy to fix with a customstatic 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.EDIT:
Here's a slightly more verbose (but equally inefficient) variant without the overflow issue.
我认为我的解决方案更加优雅和简单,因此更容易验证其正确性:
相对于其他解决方案的优点:
I think my solution is more elegant and simple, and therefore easier to verify as correct:
Benefits over the other solutions:
以下是如何以“LINQish”方式解决问题:
由于数组复制和重建,该解决方案当然不如传统的循环解决方案高效。
Here is how to solve the problem in a "LINQish" way:
Due to the array copying and reconstruction, this solution - of course - is not as efficient as the traditional solution with loops.
不是 100% Linq,但这是一个通用变体:
Not 100% Linq but here's a generic variant:
这是我的尝试:
这将返回形成子序列的特定项目,并允许任何类型的项目和任何标准定义,只要它可以通过比较相邻项目来确定即可。
Here's my shot at it:
This returns the specific items that form the sub-sequences and permits any type of item and any definition of criteria so long as it can be determined by comparing adjacent items.
对数组进行排序,然后创建另一个数组,该数组是每个元素与前一个元素之间的差异
Now iterate through the difference array; if the difference equlas 1, increase the count of a variable, sequenceLength, by 1. If the difference is > 1, check the sequenceLength if it is >=2 then you have a sequence of at at least 3 consecutive elements. Then reset sequenceLenght to 0 and continue your loop on the difference array.
What about sorting the array then create another array that is the difference between each element the previous one
Now iterate through the difference array; if the difference equlas 1, increase the count of a variable, sequenceLength, by 1. If the difference is > 1, check the sequenceLength if it is >=2 then you have a sequence of at at least 3 consecutive elements. Then reset sequenceLenght to 0 and continue your loop on the difference array.
这是我在 F# 中提出的一个解决方案,将其转换为 C# LINQ 查询应该相当容易,因为 Fold 几乎等同于 LINQ 聚合运算符。
Here is a solution I knocked up in F#, it should be fairly easy to translate this into a C# LINQ query since fold is pretty much equivalent to the LINQ aggregate operator.
Linq 并不是万能的解决方案,有时您最好使用简单的循环。这是一个解决方案,只需一点 Linq 即可对原始序列进行排序并过滤结果
Linq isn't the solution for everything, sometimes you're better of with a simple loop. Here's a solution, with just a bit of Linq to order the original sequences and filter the results
我想到了同样的事情 Jon:要表示一系列连续整数,您真正需要的只是两个微不足道的整数!所以我将从这里开始:
从那里,您可以编写一个静态方法来返回一堆与序列的连续数字相对应的
Range
值。演示:
输出:
I thought of the same thing as Jon: to represent a range of consecutive integers all you really need are two measly integers! So I'd start there:
From there, you can write a static method to return a bunch of these
Range
values corresponding to the consecutive numbers of your sequence.Demo:
Output:
这是我对这个问题的 LINQ-y 看法:
SortedSet
而不是.OrderBy().Distinct()
list.Zip(list.Skip(1))
结合起来Here's my LINQ-y take on the problem:
SortedSet
instead of.OrderBy().Distinct()
list.Zip(list.Skip(1))
这是使用字典而不是排序的解决方案......
它将项目添加到字典中,然后对于每个值在上方和下方递增以找到最长的序列。
它不是严格意义上的 LINQ,尽管它确实使用了一些 LINQ 函数,而且我认为它比纯 LINQ 解决方案更具可读性。
Here's a solution using a Dictionary instead of a sort...
It adds the items to a Dictionary, and then for each value increments above and below to find the longest sequence.
It is not strictly LINQ, though it does make use of some LINQ functions, and I think it is more readable than a pure LINQ solution..