Farshad
Farshad

Reputation: 3150

Find a subsequence in a list

Lets assume that we are looking for a sequence in a list and this sequence should satisfy some conditions, for example I have a series of numbers like this:

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

I need to find the largest sequence so that its consecutive elements have a difference of 1, So what I expected to get is:

[12,13,14,15]

I'm curious if there is any way to get in Kotlin Sequence or inline functions like groupBy or something else.

PS: I know how to create sequences, the question is how to evaluate and extract some sequences with given conditions.

Upvotes: 1

Views: 493

Answers (1)

Neo
Neo

Reputation: 2039

There is no built in functionality for this "sequence" recognition, but you could solve it with the fold operation:

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

Upvotes: 1

Related Questions