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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,140 questions

56,014 answers

573 users

How to mirror a matrix across the main diagonal in Kotlin

1 Answer

0 votes
fun mirrorMatrix(matrix: Array<Array<Int>>): Array<Array<Int>> {
    val n = matrix.size

    // Validate that the matrix is square
    if (matrix.any { it.size != n }) {
        throw IllegalArgumentException("The matrix must be square (NxN).")
    }

    // Perform the mirroring by swapping elements across the main diagonal
    for (i in 0 until n) {
        for (j in i + 1 until n) { // Only traverse above the diagonal
            // Swap elements (i, j) and (j, i)
            val temp = matrix[i][j]
            matrix[i][j] = matrix[j][i]
            matrix[j][i] = temp
        }
    }

    return matrix
}

fun main() {
    val matrix = arrayOf(
        arrayOf(1, 2, 3),
        arrayOf(4, 5, 6),
        arrayOf(7, 8, 9)
    )

    println("Original Matrix:")
    matrix.forEach { println(it.joinToString(" ")) }

    // Mirror the matrix across the main diagonal
    val mirroredMatrix = mirrorMatrix(matrix)

    println("\nMirrored Matrix:")
    mirroredMatrix.forEach { println(it.joinToString(" ")) }
}



  
/*
run:

The last digit is: 2

*/

 



answered Aug 28, 2025 by avibootz

Related questions

...