Clojure:从序列中查找连续项
在 Clojure 程序中,我有一个数字序列:
(2 3 4 6 8 1)
我想找到其中项目连续的最长子序列:
(2 3 4)
我假设它将涉及 (take-while ...)
或(减少...)
。
有什么想法吗?
澄清:我需要最长的初始连续项目列表。我确信,容易多了。感谢您对我最初提出的更困难的问题的解决方案。
In a Clojure program, I have a sequence of numbers:
(2 3 4 6 8 1)
I want to find the longest sub-sequence where the items are sequential:
(2 3 4)
I am assuming that it will involve (take-while ...)
or (reduce ...)
.
Any ideas?
Clarification: I need the longest initial list of sequential items. Much easier, I'm sure. Thanks for the solutions to the more difficult problem I initially posed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只对最长的初始序列感兴趣,那么它是 1-liner:
If you are only interested in the longest initial sequence, it's a 1-liner:
考虑到OP对这个问题的评论——这完全改变了游戏! -- 这可以写得非常简单:
注意,这实际上是懒惰的。由于本地清算,我预计它不会占据双子的头部。另一个版本:
不过,问题的原始版本更有趣! :-) 可以使用上面的方法构建一个超级简单的解决方案,但是当然,这会比使用
reduce
性能低得多。我将看看我是否有任何与 zmila 和 dnolen 的解决方案有本质不同的东西——但仍然具有相当的性能——稍后添加到该线程的该部分。 (我猜不太可能。)Taking into account the OP's comment on the question -- which completely changes the game! -- this can be written very simply:
Note that this is actually lazy. I expect it not to hold onto the head of
doubletons
thanks to locals clearing. Another version:The original version of the question is more fun, though! :-) A super-simple solution to that could be built using the above, but of course that would be significantly less performant than using
reduce
. I'll see if I have anything substantially different from zmila's and dnolen's solutions -- and yet still reasonably performant -- to add to that part of this thread later. (Not very likely, I guess.)对原文的回答:
对于那些感兴趣的人来说,一个更通用的解决方案:
我认为这要好得多。
Answer to original:
A more generic solution for those interested:
I think this is much better.