i’m wondering if there’s a clever way to chunk a list of Ints based on the delta between the first and last elements. i.e. chunks should be created such that (lastElement - firstElement <= X).
originalList = listOf(1, 2, 3, 4, 5, 10, 11, 14, 15, 19, 22);
chunks = originalList.chunkMaxDifference(5);
chunks = ((1, 2, 3, 4, 5), (10, 11, 14, 15), (19, 22))
i came up with this, but i wonder if there’s a better way:
fun List<Int>.chunkMaxDifference(maxDifference: Int): List<List<Int>> {
val chunks = mutableListOf<List<Int>>()
if (this.isEmpty()) {
return chunks
}
var currentChunk = mutableListOf<Int>(first())
chunks.add(currentChunk)
// Ignore the first value which we already put in the current chunk
subList(1, size).forEach {
if (it - currentChunk.first() > maxDifference) {
currentChunk = mutableListOf(it)
chunks.add(currentChunk)
} else {
currentChunk.add(it)
}
}
return chunks
}