Marc Javier
12/05/2021, 10:59 PMephemient
12/05/2021, 11:03 PMMarc Javier
12/05/2021, 11:06 PMholgerbrandl
12/05/2021, 11:16 PMfold
ing or similar, but have no clue how to implement it elegantly.Michael Böiers
12/06/2021, 9:51 PMlistOf("a", "a", "b", "c", "c", "a", "a")
.fold(mutableListOf<Pair<String, Int>>()) { acc, s ->
if (acc.isEmpty() || acc.last().first != s)
acc.add(s to 1)
else
acc[acc.size-1] = s to acc.last().second + 1
acc
}.toList()
fun <T> Iterable<T>.runLengths() = fold(mutableListOf<Pair<T, Int>>()) { acc, t ->
acc.apply {
if (acc.isEmpty() || acc.last().first != t)
acc.add(t to 1)
else
acc[acc.size-1] = t to acc.last().second + 1
}
}.toList()
listOf("a", "a", "b", "c", "c", "a", "a")
.runLengths()
ephemient
12/06/2021, 9:55 PMMichael Böiers
12/06/2021, 10:04 PMfun <T> Iterable<T>.runLengths() = mutableListOf<Pair<T, Int>>().run {
for (t in this@runLengths)
if (isEmpty() || last().first != t) add(t to 1) else set(size - 1, t to last().second + 1)
toList()
}
listOf("a", "a", "b", "c", "c", "a", "a").runLengths()
fun <T> Iterable<T>.runLengths() = buildList<Pair<T, Int>> {
for (t in this@runLengths)
if (isEmpty() || last().first != t) add(t to 1) else set(size - 1, t to last().second + 1)
}
listOf("a", "a", "b", "c", "c", "a", "a").runLengths()
ephemient
12/06/2021, 10:09 PM