Venkat
05/03/2020, 11:59 PMcrummy
05/04/2020, 12:00 AMDominaezzz
05/04/2020, 12:10 AMscan
to count the number of `o=`s before (and including) each element, then group by this count.Jakub Pi
05/04/2020, 3:47 AMfun <A> List<A>.splitBy(pred : (A) -> Boolean) : List<List<A>> {
if(size == 0) return listOf()
val loc = indexOfLast(pred)
if(loc == -1) return listOf(this)
return subList(0, loc).splitBy(pred) + listOf(subList(loc, size))
}
val list = listOf("o=one", "t=two", "t=two", "f=four", "o=one", "t=two", "s=seven", "o=one")
list.splitBy { it.startsWith("o=") }
//[[o=one, t=two, t=two, f=four], [o=one, t=two, s=seven], [o=one]]
It's not stack safe or necessarily efficient, but very readable.Jakub Pi
05/04/2020, 4:11 AMfun <A> List<A>.splitBy(pred : (A) -> Boolean) : List<List<A>> {
tailrec fun List<A>.go(pred : (A) -> Boolean, suffix : List<List<A>>) : List<List<A>> {
val loc = indexOfLast(pred)
return when {
size == 0 -> suffix
loc == -1 -> listOf(this) + suffix
else -> subList(0, loc).go(pred, listOf(subList(loc,size)) + suffix)
}
}
return go(pred, listOf())
}
Venkat
05/04/2020, 11:07 AMDominaezzz
05/04/2020, 2:46 PM@ExperimentalStdlibApi
fun dummy() {
val list = listOf("o=one", "t=two", "t=two", "f=four", "o=one", "t=two", "s=seven", "o=one")
list.asSequence()
.map { (if (it[0] == 'o') 1 else 0) to it }
.scanReduce { (count, _), (inc, s) -> (count + inc) to s }
.groupBy({ it.first }, { it.second })
.values
.toList()
}