How to count the number of sorted rows in either increasing or decreasing order in a matrix using Scala

1 Answer

0 votes
object SortedMatrixCounter {
  def sortedCount(matrix: Array[Array[Int]]): Int = {
    var result = 0

    // Check for strictly increasing rows
    for (row <- matrix) {
      if (row.sliding(2).forall { case Array(a, b) => a < b }) {
        result += 1
      }
    }

    // Check for strictly decreasing rows
    for (row <- matrix) {
      if (row.sliding(2).forall { case Array(a, b) => a > b }) {
        result += 1
      }
    }

    result
  }

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

    println(s"Number of sorted rows: ${sortedCount(matrix)}")
  }
}



/*
run:

Number of sorted rows: 3

*/

 



answered Oct 1 by avibootz
...