How to create a sorted unique list from a matrix in Kotlin

1 Answer

0 votes
/*
    Create a sorted unique list (lst) from a matrix.
    Steps:
      1. Flatten matrix into lst
      2. Sort lst
      3. Remove duplicates (distinct)
*/

fun makeSortedUniqueLst(mat: Array<Array<Int>>): List<Int> {
    // Flatten matrix into lst
    val lst = mat.flatten()

    // Sort lst and remove duplicates
    return lst.sorted().distinct()
}

fun main() {
    val mat = arrayOf(
        arrayOf(5, 1, 17, 3, 8, 2, 1, 9),
        arrayOf(3, 5, 7, 4, 2, 3, 4, 1),
        arrayOf(9, 1, 8, 2, 3, 88, 17, 5)
    )

    val lst = makeSortedUniqueLst(mat)

    lst.forEach { print("$it ") }
}



/*
run:

1 2 3 4 5 7 8 9 17 88

*/

 



answered May 7 by avibootz
...