nwh
06/03/2020, 7:04 PM111212221
I want my output to be:
[111], [2], [1], [222], [1]
Dominaezzz
06/03/2020, 7:09 PMDominaezzz
06/03/2020, 7:09 PMnwh
06/03/2020, 7:11 PMgroupBy
except split into lists that are in ordernil2l
06/03/2020, 7:19 PMlist.fold()
nwh
06/03/2020, 7:21 PMDominaezzz
06/03/2020, 7:30 PM//val input = listOf(1, 1, 1, 2, 1, 2, 2, 2, 1)
fun firstIdea(input: List<Int>): List<List<Int>> {
val indicesOfChange = input.asSequence().zipWithNext { a, b -> a != b }
.mapIndexedNotNull { index, changed -> if (changed) index else null }
val sublistIndexes = sequence {
yield(0)
yieldAll(indicesOfChange)
yield(input.lastIndex)
}
return sublistIndexes.zipWithNext { start, endInclusive -> input.subList(start, endInclusive + 1) }.toList()
}
Dominaezzz
06/03/2020, 7:31 PMGeert
06/03/2020, 7:31 PMDominaezzz
06/03/2020, 7:34 PMnil2l
06/03/2020, 7:39 PM"111212221".map { it.toString().toInt() }
.fold(emptyList<List<Int>>()) { acc, i ->
val lastGroup = acc.takeIf { it.isNotEmpty()}?.last()
val last = lastGroup?.last()
if (last != i) {
// start new group
acc + listOf(listOf(i))
} else {
// add to the last group
acc.take(acc.size - 1) + listOf(lastGroup + i)
}
}
nwh
06/03/2020, 7:41 PMnwh
06/03/2020, 7:41 PMDominaezzz
06/03/2020, 7:41 PMnil2l
06/03/2020, 7:41 PMPair
as acc
(to not recreate last every time)
Pair< List<List<Int>>, List<Int> >
But idea is so.nwh
06/03/2020, 7:42 PMnil2l
06/03/2020, 7:44 PMnwh
06/03/2020, 7:45 PMgroupInPlace
for ultimate readabilitynil2l
06/03/2020, 7:45 PMnwh
06/03/2020, 7:46 PMnil2l
06/03/2020, 7:46 PMDominaezzz
06/03/2020, 7:47 PMnil2l
06/03/2020, 7:47 PMDominaezzz
06/03/2020, 7:48 PMcontiguousGroupBy
. It's a mouthful though.Milan Hruban
06/03/2020, 7:51 PMinline fun <T> Iterable<T>.adjacentGroupBy(keySelector: (T) -> Any? = { it }): List<List<T>> =
this.fold(listOf<MutableList<T>>()) { acc, element ->
if (acc.isNotEmpty() && keySelector(acc.last().last()) == keySelector(element)) {
acc.also { it.last().add(element) }
} else {
acc + listOf(mutableListOf(element))
}
}
Milan Hruban
06/03/2020, 7:53 PMMichael de Kaste
06/04/2020, 8:03 AMinput.split("""(?<=(.))(?!\1)""".toRegex())
EyeCon
06/04/2020, 1:00 PM