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

1 Answer

0 votes
object MatrixUtils {
  def isSquareMatrix[T](matrix: Seq[Seq[T]]): Boolean = {
    val size = matrix.length
    
    matrix.forall(_.length == size)
  }
}

object Main extends App {
  val matrix = Seq(
    Seq(1, 2, 3),
    Seq(4, 5, 6),
    Seq(7, 8, 9)
  )

  if (MatrixUtils.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
...