Sam Stone
10/26/2022, 5:29 PMjw
10/26/2022, 5:33 PMephemient
10/26/2022, 5:35 PMephemient
10/26/2022, 5:36 PMephemient
10/26/2022, 5:42 PMfun <T> Iterable<T>.splitWhen(predicate: (T) -> Boolean): List<List<T>> {
var counter = 0
return groupBy { if (predicate(it)) ++counter else counter }.values.map { it.dropWhile(predicate) }
}
listOf(1, 2, 0, 3, 0, 0, 4).splitWhen { it == 0 } // [[1, 2], [3], [], [4]]
Sam Stone
10/26/2022, 9:56 PMfun <E> List<E>.split(includeDelimiter: Boolean = false, predicate: (E) -> Boolean): List<List<E>> {
return flatMapIndexed { index, x ->
when {
index == 0 || index == lastIndex -> listOf(index)
predicate(x) -> listOf(index - 1, index + 1)
else -> emptyList()
}
}
.windowed(size = 2, step = 2) { (from, to) -> slice( (if(includeDelimiter) (from - 1).coerceAtLeast(0) else from)..to) }
}
ephemient
10/26/2022, 10:01 PMephemient
10/26/2022, 10:09 PMfun <E> Iterable<E>.split(predicate: (E) -> Boolean): List<List<E>> = buildList {
val last = this@split.fold(mutableListOf<E>()) { acc, elem ->
if (predicate(elem)) {
add(acc.orEmpty())
mutableListOf()
} else {
acc.add(elem)
acc
}
}
if (last.isNotEmpty()) add(last)
}
over either of the aboveSam Stone
10/26/2022, 11:40 PMgroupBy
,map
, dropWhile
.ephemient
10/26/2022, 11:51 PMgroupBy
iterates N
elements once. map
iterates the groups and dropWhile
iterates over at most 1 element of each group, and even if it iterated the whole group, it would still sum to at most N
total.