bbaldino
03/06/2019, 8:17 PMoriginalList = 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
}
Pavlo Liapota
03/06/2019, 9:07 PMsubList(1, size)
-> drop(1)
Luke
03/06/2019, 9:16 PMfun 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
}
}
Pavlo Liapota
03/06/2019, 9:20 PMLuke
03/06/2019, 9:22 PMPavlo Liapota
03/06/2019, 9:24 PMAll Threads
windowbbaldino
03/06/2019, 9:41 PM