I wrote a `List<T>.chunkedBy` function that ...
# advent-of-code
a
I wrote a
List<T>.chunkedBy
function that some people might find useful
Copy code
fun <T, R> List<T>.chunkedBy(key: (T) -> R): List<Pair<R, List<T>>> {
    val chunks = mutableListOf<Pair<R, List<T>>>()
    var startingIndex = 0
    forEachIndexed { index, t ->
        val value = key(t)
        if (value != key(this[startingIndex])) {
            chunks += key(this[startingIndex]) to subList(startingIndex, index)
            startingIndex = index
        }
    }
    if (startingIndex < size) chunks += key(this[startingIndex]) to subList(startingIndex, size)
    return chunks
}
Example
Copy code
fun main() {
    (1..100).toList()
        .chunkedBy { sqrt(it.toDouble()).toInt().toDouble() == sqrt(it.toDouble()) }
        .let { println(it) }
}
Outputs:
Copy code
[(true, [1]), (false, [2, 3]), (true, [4]), (false, [5, 6, 7, 8]), (true, [9]), (false, [10, 11, 12, 13, 14, 15]), (true, [16]), (false, [17, 18, 19, 20, 21, 22, 23, 24]), (true, [25]), (false, [26, 27, 28, 29, 30, 31, 32, 33, 34, 35]), (true, [36]), (false, [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]), (true, [49]), (false, [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]), (true, [64]), (false, [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80]), (true, [81]), (false, [82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]), (true, [100])]
b
wouldn't it work with groupBy ?
oh I see
😂 1