https://kotlinlang.org logo
Title
b

bbaldino

03/06/2019, 8:17 PM
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
}
p

Pavlo Liapota

03/06/2019, 9:07 PM
subList(1, size)
->
drop(1)
l

Luke

03/06/2019, 9:16 PM
this is what I came up with. I only tested your example but I leave this here:
fun List<Int>.chunkMaxDifference(maxDifference: Int): List<List<Int>> {
    return fold(mutableListOf<MutableList<Int>>()) { acc, item ->
        val lastChunk = acc.lastOrNull() ?: return@fold acc.also { acc.add(mutableListOf(item)) }
        val smallestValue = lastChunk.firstOrNull() ?: return@fold acc.also { lastChunk + item }
        if(smallestValue + maxDifference < item) acc.add(mutableListOf(item))
        else lastChunk.add(item)
        acc
    }
}
p

Pavlo Liapota

03/06/2019, 9:20 PM
And this is my suggestion 🙂 https://pl.kotl.in/S17qF2T8N
l

Luke

03/06/2019, 9:22 PM
gee, +1 for the shorten link to the playground
p

Pavlo Liapota

03/06/2019, 9:24 PM
Yea, reading code in a thread can be a pain, unless you are looking at it in
All Threads
window
b

bbaldino

03/06/2019, 9:41 PM
thanks! nice solutions