adamratzman
12/04/2020, 7:19 PMList<T>.chunkedBy
function that some people might find usefuladamratzman
12/04/2020, 7:19 PMfun <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
}
adamratzman
12/04/2020, 7:19 PMfun main() {
(1..100).toList()
.chunkedBy { sqrt(it.toDouble()).toInt().toDouble() == sqrt(it.toDouble()) }
.let { println(it) }
}
Outputs:
[(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])]
bjonnh
12/04/2020, 8:52 PMbjonnh
12/04/2020, 8:52 PM