How to flatten a 2D array into a sorted one-dimensional array in Kotlin

1 Answer

0 votes
// Function that flattens a 2D array and returns a sorted 1D list
fun flattenAndSort(array2d: Array<IntArray>): List<Int> {

    // 1. Flatten the 2D array into a single list
    //    flatMap converts each row into a list and concatenates them
    val flattened = array2d.flatMap { it.toList() }

    // 2. Sort the flattened list
    return flattened.sorted()
}

fun main() {
    val array2d = arrayOf(
        intArrayOf(4, 5, 3),
        intArrayOf(30, 20),
        intArrayOf(10),
        intArrayOf(1, 2, 6, 7, 8)
    )

    val arr = flattenAndSort(array2d)

    // Print result as comma‑separated values
    println(arr.joinToString(", "))
}



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered 2 hours ago by avibootz

Related questions

...