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

1 Answer

0 votes
// Function that flattens a 2D array, sorts it, removes duplicates,
// and returns a new sorted list with unique values
fun flattenSortUnique(array2d: Array<IntArray>): List<Int> {

    // 1. Flatten the 2D array into a 1D list
    val flat = array2d.flatMap { it.asList() }

    // 2. Sort the flattened list
    val sorted = flat.sorted()

    // 3. Remove duplicates using distinct
    val unique = sorted.distinct()

    return unique
}

fun main() {

    val array2d = arrayOf(
        intArrayOf(4, 3, 3, 2, 4),
        intArrayOf(30, 10, 10),
        intArrayOf(10, 30),
        intArrayOf(1, 1, 6, 7, 7, 7, 8)
    )

    val arr = flattenSortUnique(array2d)

    // Print results
    arr.forEach { n ->
        print("$n\t")
    }
}


/*
run

1	2	3	4	6	7	8	10	30	

*/

 



answered 2 hours ago by avibootz

Related questions

...