How to check if a matrix is Toeplitz or not in Scala

1 Answer

0 votes
// A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements

object ToeplitzMatrix {
  def isToeplitz(matrix: Array[Array[Int]]): Boolean = {
    val rows = matrix.length
    val cols = matrix(0).length
    var result = true

    for (i <- 1 until rows) {
      for (j <- 1 until cols) {
        println(s"$i $j - ${matrix(i)(j)} : ${matrix(i - 1)(j - 1)}")
        if (matrix(i)(j) != matrix(i - 1)(j - 1)) {
          result = false
        }
      }
      println("-----------")
    }

    result
  }

  def main(args: Array[String]): Unit = {
    val matrix = Array(
      Array(2, 7, 9, 8),
      Array(4, 2, 7, 9),
      Array(3, 4, 2, 7),
      Array(0, 3, 4, 2),
      Array(6, 0, 3, 4)
    )

    if (isToeplitz(matrix)) {
      println("Matrix is a Toeplitz")
    } else {
      println("Matrix is not a Toeplitz")
    }
  }
}
 
   
   
/*
run:
     
1 1 - 2 : 2
1 2 - 7 : 7
1 3 - 9 : 9
-----------
2 1 - 4 : 4
2 2 - 2 : 2
2 3 - 7 : 7
-----------
3 1 - 3 : 3
3 2 - 4 : 4
3 3 - 2 : 2
-----------
4 1 - 0 : 0
4 2 - 3 : 3
4 3 - 4 : 4
-----------
Matrix is a Toeplitz
 
*/

 



answered Jan 31 by avibootz
edited Jan 31 by avibootz

Related questions

1 answer 42 views
1 answer 39 views
1 answer 44 views
1 answer 48 views
1 answer 45 views
...