Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,633 questions

55,368 answers

573 users

How to sort each column of a matrix with strings in Kotlin

1 Answer

0 votes
fun sortColumns(matrix: Array<Array<String>>) {
    val rows = matrix.size
    val cols = matrix[0].size

    for (col in 0 until cols) {
        // Extract column into a list
        val column = List(rows) { matrix[it][col] }.sorted()

        // Place sorted values back into the matrix
        for (row in 0 until rows) {
            matrix[row][col] = column[row]
        }
    }
}

fun printMatrix(matrix: Array<Array<String>>) {
    matrix.forEach { row -> println(row.joinToString(" ")) }
}

fun main() {
    val matrix = arrayOf(
        arrayOf("ccc", "zzzz", "yyyyyy"),
        arrayOf("eeee", "aaa", "ffff"),
        arrayOf("uu", "hhh", "uuu"),
        arrayOf("bbb", "gg", "x")
    )

    println("Original Matrix:")
    printMatrix(matrix)

    sortColumns(matrix)

    println("\nSorted Matrix:")
    printMatrix(matrix)
}


 
  
/*
run:
  
Original Matrix:
ccc zzzz yyyyyy
eeee aaa ffff
uu hhh uuu
bbb gg x

Sorted Matrix:
bbb aaa ffff
ccc gg uuu
eeee hhh x
uu zzzz yyyyyy
  
*/

 



answered Jun 2, 2025 by avibootz
...