How to check whether a matrix is a square matrix in Kotlin

1 Answer

0 votes
fun <T> isSquareMatrix(matrix: List<List<T>>): Boolean {
    val size = matrix.size
    
    return matrix.all { it.size == size }
}

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

    if (isSquareMatrix(matrix)) {
        println("The matrix is a square matrix.")
    } else {
        println("The matrix is not a square matrix.")
    }
}



/*
run:

The matrix is a square matrix.

*/

 



answered Oct 7, 2025 by avibootz
...