Kotlin 在列表中查找子序列

Kotlin 在列表中查找子序列,kotlin,Kotlin,假设我们正在列表中查找一个序列,该序列应满足某些条件,例如,我有一系列如下数字: [1,2,4,6,7,8,12,13,14,15,20] 我需要找到最大的序列,使其连续元素的差值为1,因此我希望得到: [12,13,14,15] 我很好奇是否有任何方法可以进入KotlinSequence或类似于groupBy或其他内联函数 PS:我知道如何创建序列,问题是如何在给定条件下评估和提取一些序列 此“序列”识别没有内置功能,但您可以使用折叠操作解决此问题: val result = listOf

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

[1,2,4,6,7,8,12,13,14,15,20]
我需要找到最大的序列,使其连续元素的差值为1,因此我希望得到:

[12,13,14,15]
我很好奇是否有任何方法可以进入Kotlin
Sequence
或类似于
groupBy
或其他内联函数


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

此“序列”识别没有内置功能,但您可以使用
折叠操作解决此问题:

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
val result=listOf(1,2,3,12,13,14,15)
.distinct()//删除重复项
.sorted()//按最低优先级排序
.fold(mutableListOf()到mutableListOf()){(currentList,AllList),currentItem->
if(currentList.isEmpty()){//仅适用于第一项
可变列表(currentItem)到所有列表
}否则{
如果(currentItem-currentList.max()!!==1){//您的自定义序列识别“差异为1”
currentList.apply{add(currentItem)}到所有列表
}否则{
mutableListOf(currentItem)到AllList.apply{add(currentList)}//Next
}
}
}
.let{it.second.apply{add(it.first)}//add last list
.maxBy{it.size}//我们需要最长的模式-它将占据堆栈的第一个-它可以是多个。
//如果您需要更精确的列表,请根据您的条件对其进行排序