How to flatten a list of list with a specific strategy

Viewed 349

I got this list of lists:

[[1, 2, 3], [4, 5], [6]] = listOf(listOf(1,2,3), listOf(4,5), listOf(6))

If I'm using the flatten method, the result would be:

[1, 2, 3, 4, 5, 6] = listOf(1,2,3,4,5,6)

The output I want would be kind of round robin flatten taking the first N elements of each list for flattening...

So if N=1: [1, 4, 6, 2, 5, 3]

if N=2: [1, 2, 4, 5, 6, 3]

if N=3: [1, 2, 3, 4, 5, 6]

I suppose it is achievable by using some mutable lists but it would be pretty ugly and not functional at all.

3 Answers

This should do the trick even though the syntax is not that good, in my opinion. There's probably a way to optimize the following solution but I think it's a good place to start.

val numberOfElements = 1
val numbers = listOf(listOf(1, 2, 3), listOf(4, 5), listOf(6))
val result = numbers.flatMap {
        it.take(numberOfElements)
    }.union(numbers.flatMap { if (it.size - numberOfElements > 0) {
        it.takeLast(it.size - numberOfElements)
    } else {
        emptyList()
    } })

println(result) 
// numberOfElements = 1 --> [1, 4, 6, 2, 3, 5]
// numberOfElements = 2 --> [1, 2, 4, 5, 6, 3]
// numberOfElements = 3 --> [1, 2, 3, 4, 5, 6]

val numbers = listOf(listOf(1, 2, 3), listOf(4, 5), listOf(6))
println(numbers.roundRobin(1)) // [1, 4, 6, 2, 5, 3]
println(numbers.roundRobin(2)) // [1, 2, 4, 5, 6, 3]
println(numbers.roundRobin(3)) // [1, 2, 3, 4, 5, 6]


fun <T> List<List<T>>.roundRobin(count: Int): List<T> {
    return flatMap { it.chunked(count)
                        .mapIndexed { i, v -> i to v } }
        .sortedBy { it.first }
        .flatMap { it.second }
}

You can try this. It is a recursive function.

var flattenedList : MutableList<Int> = ArrayList()

fun List<*>.flatten(){
    for(i in this){
        when(i){
            is Int -> {
                flattenedList.add(i)
            }
            is List<*> -> {
                i.flatten()
            }
        }
    }
}

fun main(){
    var list = listOf(listOf(1,2,3), listOf(4,5,6), 7)
    list.flatten()
    println(flattenedList.toString())
}
Related