gpt4 book ai didi

kotlin - 在列表中查找子序列

转载 作者:行者123 更新时间:2023-12-02 13:36:27 24 4
gpt4 key购买 nike

假设我们正在列表中寻找一个序列,并且该序列应满足一些条件,例如我有一系列数字,如下所示:

[1,2,4,6,7,8,12,13,14,15,20]

我需要找到最大的序列,以使其连续的元素相差1,所以我期望得到的是:
[12,13,14,15]

我很好奇是否有任何方法可以获取Kotlin SequencegroupBy之类的内联函数或其他内容。

PS :我知道如何创建序列,问题是如何在给定条件下评估和提取一些序列。

最佳答案

此“序列”识别没有内置的功能,但您可以使用fold操作来解决它:

val result = listOf(1, 2, 3, 12, 13, 14, 15)
.distinct() // remove duplicates
.sorted() // by lowest first
.fold(mutableListOf<Int>() to mutableListOf<List<Int>>()) { (currentList, allLists), currentItem ->

if (currentList.isEmpty()) { // Applies only to the very first item
mutableListOf(currentItem) to allLists
} else {

if (currentItem - currentList.max()!! == 1) { // Your custom sequence recognition 'difference of 1'
currentList.apply { add(currentItem) } to allLists
} else {
mutableListOf(currentItem) to allLists.apply { add(currentList) } // Next
}

}
}
.let { it.second.apply { add(it.first) } } // Add last list
.maxBy { it.size } // We need the longest pattern - which will take first of the stack - it could be multiple.
// If you need more precise list, sort them by your criteria

关于kotlin - 在列表中查找子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com