holgerbrandl
12/05/2021, 10:51 PMequals
). E.g. how to transform
listOf("A", "A", "B", "C", "C", "C", "C", "A", "A")
// to
listOf("A" to 2, "B" to 1, "C" to 4, "A" to 2)
ephemient
12/05/2021, 11:15 PMfun <T> Collection<T>.runLengths() = buildList {
val last = this@runLengths.withIndex().fold(null) { prev: IndexedValue<T>?, cur ->
when {
prev == null -> cur
prev.value == cur.value -> prev
else -> {
add(prev.value to cur.index - prev.index)
cur
}
}
}
last?.let { add(it.value to this@runLengths.size - it.index) }
}
holgerbrandl
12/06/2021, 10:51 AMSzymon Jeziorski
12/08/2021, 7:36 PMfun <T> Collection<T>.runLengths() = takeIf { isNotEmpty() }?.let {
buildList {
it.fold(it.first() to 0) { (prev, count), cur ->
if (cur == prev) (prev to count + 1) else {
add(prev to count)
cur to 1
}
}.run(::add)
}
}.orEmpty()
holgerbrandl
12/08/2021, 7:47 PMephemient
12/08/2021, 7:51 PMholgerbrandl
12/08/2021, 7:55 PM