在列表中找到子序列

时间:2019-04-18 20:04:04

标签: kotlin

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

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

我需要找到最大的序列,以便其连续元素之间的差为1,所以我希望得到的是:

[12,13,14,15]

我很好奇,是否有任何办法可以通过kotlin SequencegroupBy之类的内联函数或其他方式来实现...
PS :我知道如何创建序列,问题是如何在给定条件下评估和提取一些序列
谢谢

1 个答案:

答案 0 :(得分:0)

此“序列”识别没有内置功能,但是您可以使用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