Created
October 15, 2020 04:28
-
-
Save kiwiandroiddev/20d6410d9c2ac459d58d117292f31798 to your computer and use it in GitHub Desktop.
Kotlin function to remove duplicate consecutive elements in a list, up to maxN duplicate consecutive elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Removes duplicate consecutive elements in a list, up to maxN duplicate consecutive elements | |
* per group. | |
* Ex. where maxN = 2: | |
* [0, 0, 1, 2, 2, 4, 4, 4, 4] => [0, 1, 2, 4, 4] | |
*/ | |
fun <T> List<T>.normalize(maxN: Int): List<T> { | |
var nextIndexToConsider = 0 | |
return windowed(size = maxN, step = 1, partialWindows = true) | |
.mapIndexed { index, window -> | |
val shouldSkipThisItem = index < nextIndexToConsider | |
if (shouldSkipThisItem) { | |
emptyList() | |
} else { | |
val consecutiveRepeatedItemsInThisWindow = window.takeWhile { it == window.first() } | |
nextIndexToConsider += consecutiveRepeatedItemsInThisWindow.size | |
listOf(window.first()) | |
} | |
}.flatten() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment