Prolog:有没有办法在列表中找到最长的连续数序列并获得其长度?
给定5个随机数字的列表(数字范围从1到13),即[1,6,11,12,13],我如何找到连续最长的数字序列(即[11,12,13 ])它的长度必须更大或等于3,并且还必须获得长度?
Given a list of 5 random natural numbers (the number's range is from 1 to 13), i.e. [1,6,11,12,13], how can I find out the longest consecutive number sequence (i.e. [11,12,13]) that its length must be larger or equal to 3, and also get its length?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以遍历列表,跟踪当前序列及其长度以及迄今为止找到的最大序列和长度。
处理完所有列表后,您可以检查最大长度是否 >= 3 并选择正确的输出:
示例运行:
You can traverse the list keeping track of the current sequence and its length along with the maximum sequence and length found so far.
After processing all the list you can check whether the maximum length is >= 3 and select the proper output:
Sample runs: