Skip to content

Instantly share code, notes, and snippets.

@kiwiandroiddev
Created October 15, 2020 04:28
Show Gist options
  • Save kiwiandroiddev/20d6410d9c2ac459d58d117292f31798 to your computer and use it in GitHub Desktop.
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
/**
* 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