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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

How to rotate square matrix 90 degrees to the left in Kotlin

1 Answer

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

/**
 * Rotates a square matrix 90 degrees to the left (counterclockwise).
 * param matrix - The square matrix to rotate.
 */
fun rotateMatrix90DegreesLeft(matrix: Array<IntArray>) {
    val len = matrix.size

    // Validate input: Ensure it's a square matrix
    if (!matrix.all { it.size == len }) {
        throw IllegalArgumentException("Input must be a square matrix.")
    }

    // Perform the rotation in-place
    for (layer in 0 until len / 2) {
        val first = layer
        val last = len - 1 - layer

        for (i in first until last) {
            val offset = i - first

            // Save the top element
            val top = matrix[first][i]

            // Move right to top
            matrix[first][i] = matrix[i][last]

            // Move bottom to right
            matrix[i][last] = matrix[last][last - offset]

            // Move left to bottom
            matrix[last][last - offset] = matrix[last - offset][first]

            // Move top to left
            matrix[last - offset][first] = top
        }
    }
}

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

    rotateMatrix90DegreesLeft(matrix)

    println("Matrix After 90° Left Rotation:")
    printMatrix(matrix)
}



/*
run:

Matrix After 90° Left Rotation:
3 6 9
2 5 8
1 4 7

*/

 



answered Oct 6, 2025 by avibootz
...