Skip to main content

Count all sorted rows in a matrix

The problem tackled here involves counting the number of rows in a given matrix that are sorted either in increasing or decreasing order. In this context, a row is considered sorted if its elements are arranged in either non-decreasing (increasing) or non-increasing (decreasing) order.

Problem Statement

Given a matrix containing integer elements, we aim to determine the count of rows that are sorted. A row is considered sorted if its elements are arranged either in non-decreasing or non-increasing order. We need to identify such rows and count them.

Example

Consider the following matrix:

1  2  3  4  5  6
4  8  7  8  5  1
9  8  7  7  5  1
7  7  6  5  4  1
7  3  2  5  1  1
5  5  5  5  5  5

In this case, the sorted rows are the first, third, fourth, and fifth rows. Therefore, the count of sorted rows is 4.

Solution Idea

Sorted rows of matrix

To solve this problem, we can iterate through each row of the matrix and check whether it is sorted in either increasing or decreasing order. We can do this by comparing each element with its adjacent element and keeping track of whether the row remains sorted. If the current row remains sorted throughout, we increment a counter.

Pseudocode

sortedRows(matrix):
    result = 0
    for each row in matrix:
        flag = True if row[0] > row[last_element] else False
        sorted = True
        for i from 1 to last_element:
            if (flag is True and row[i-1] > row[i]) or (flag is False and row[i-1] < row[i]):
                sorted = False
                break
        if sorted is True:
            result += 1
    print "Sorted Rows:", result

Algorithm Explanation

  1. Define a function sortedRows(matrix) that takes the input matrix as its parameter.
  2. Initialize a variable result to keep track of the count of sorted rows.
  3. Iterate through each row of the matrix.
  4. Determine whether the row is sorted in increasing or decreasing order by comparing the first and last elements. Set the flag accordingly.
  5. Initialize a variable sorted to True for the current row. This variable indicates whether the current row remains sorted.
  6. Iterate through the elements of the row starting from the second element.
  7. Compare the current element with its previous element. If the conditions for a sorted row are not met, set sorted to False and break out of the loop.
  8. After the inner loop completes, if sorted is still True, increment the result counter.
  9. Print the final count of sorted rows.

Code Solution

/*
  Java Program
  Count all sorted rows in a matrix
*/
public class Test
{
    // Display element of matrix
    public void showData(int[][] matrix)
    {
        int row = matrix.length;
        int col = matrix[0].length;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                System.out.print("  " + matrix[i][j]);
            }
            // Add new line
            System.out.print("\n");
        }
        // Add new line
        System.out.print("\n");
    }
    // Count sorted rows in given matrix
    public void sortedRows(int[][] matrix)
    {
        // Get size
        int row = matrix.length;
        int col = matrix[0].length;
        // Resulant counter
        int result = 0;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // If flag equal to 1 then work on decreasing order 
            // Otherwise work on increasing order 
            // Check first and last element of i row
            boolean flag = matrix[i][0] > matrix[i][col - 1];
            // Assume that is  a sorted row
            result++;
            // Check if row is sorted or not
            for (int j = 1; j < col; ++j)
            {
                if (flag == true && matrix[i][j - 1] < matrix[i][j])
                {
                    // is not sorted
                    result--;
                    break;
                }
                else if (flag == false && matrix[i][j - 1] > matrix[i][j])
                {
                    // is not sorted
                    result--;
                    break;
                }
            }
        }
        // Display calculated result
        System.out.println(" Sorted Rows : " + result);
    }
    public static void main(String[] args)
    {
        Test task = new Test();
        // Matrix of integer elements
        int[][] matrix = {
            {1 , 2 , 3 , 4 , 5 , 6},
            {4 , 8 , 7 , 8 , 5 , 1},
            {9 , 8 , 7 , 7 , 5 , 1},
            {7 , 7 , 6 , 5 , 4 , 1},
            {7 , 3 , 2 , 5 , 1 , 1},
            {5 , 5 , 5 , 5 , 5 , 5}
        };
        task.showData(matrix);
        task.sortedRows(matrix);
    }
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
// Include header file
#include <iostream>
#include <vector>
using namespace std;
/*
  C++ Program
  Count all sorted rows in a matrix
*/
class Test
{
    public:
        // Display element of matrix
        void showData(vector<vector<int>> matrix)
        {
            // Get size
            int row = matrix.size();
            int col = matrix[0].size();
            // This loop is iterating rows
            for (int i = 0; i < row; ++i)
            {
                // This loop is iterating cols
                for (int j = 0; j < col; ++j)
                {
                    cout << "  " << matrix[i][j];
                }
                // Add new line
                cout << "\n";
            }
            // Add new line
            cout << "\n";
        }
    // Count sorted rows in given matrix
    void sortedRows(vector<vector<int>> matrix)
    {
        // Get size
        int row = matrix.size();
        int col = matrix[0].size();
        // Resulant counter
        int result = 0;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // If flag equal to 1 then work on decreasing order 
            // Otherwise work on increasing order 
            // Check first and last element of i row
            bool flag = matrix[i][0] > matrix[i][col - 1];
            // Assume that is  a sorted row
            result++;
            // Check if row is sorted or not
            for (int j = 1; j < col; ++j)
            {
                if (flag == true && matrix[i][j - 1] < matrix[i][j])
                {
                    // is not sorted
                    result--;
                    break;
                }
                else if (flag == false && matrix[i][j - 1] > matrix[i][j])
                {
                    // is not sorted
                    result--;
                    break;
                }
            }
        }
        // Display calculated result
        cout << " Sorted Rows : " << result << endl;
    }
};
int main()
{
    Test *task = new Test();
    // Matrix of integer elements
    vector<vector<int>> matrix {
        {1 , 2 , 3 , 4 , 5 , 6},
        {4 , 8 , 7 , 8 , 5 , 1},
        {9 , 8 , 7 , 7 , 5 , 1},
        {7 , 7 , 6 , 5 , 4 , 1},
        {7 , 3 , 2 , 5 , 1 , 1},
        {5 , 5 , 5 , 5 , 5 , 5}
    };
    task->showData(matrix);
    task->sortedRows(matrix);
    return 0;
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
/*
  C Program 
+ Count all sorted rows in a matrix
*/
#include <stdio.h>
#define ROW 6
#define COL 6

// Display element of matrix
void show_data(int matrix[][COL])
{
    for (int i = 0; i < ROW; ++i)
    {
        for (int j = 0; j < COL; ++j)
        {
            printf("%3d", matrix[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

// Count sorted rows in given matrix
void sorted_rows(int matrix[ROW][COL])
{
    int flag = 0;
    int counter = 0;

    // This loop is iterating rows
    for (int i = 0; i < ROW; ++i)
    {
        // If flag equal to 1 then work on decreasing order 
        // Otherwise work on increasing order 
        // Check first and last element of i row
        flag = matrix[i][0] > matrix[i][COL - 1];

        // Assume that is  a sorted row
        counter++;

        // Check if row is sorted or not
        for (int j = 1; j < COL; ++j)
        {
            if (flag == 1 && matrix[i][j - 1] < matrix[i][j])
            {
                // is not sorted
                counter--;
                break;
            }
            else if (flag == 0 && matrix[i][j - 1] > matrix[i][j])
            {
                // is not sorted
                counter--;
                break;
            }
        }
    }
    // Display calculated result
    printf("  Sorted Rows : %d\n", counter);
}
int main()
{
    int matrix[ROW][COL] = 
    {
        {1 , 2 , 3 , 4 , 5 , 6},
        {4 , 8 , 7 , 8 , 5 , 1},
        {9 , 8 , 7 , 7 , 5 , 1},
        {7 , 7 , 6 , 5 , 4 , 1},
        {7 , 3 , 2 , 5 , 1 , 1},
        {5 , 5 , 5 , 5 , 5 , 5},
      
    };
    // Display matrix
    show_data(matrix);

    // count sorted row
    sorted_rows(matrix);
    return 0;
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

  Sorted Rows : 4
package main
import "fmt"
/*
  Go Program
  Count all sorted rows in a matrix
*/
type Test struct {}
func getTest() * Test {
  var me *Test = &Test {}
  return me
}
// Display element of matrix
func(this Test) showData(matrix[][] int) {
  var row int = len(matrix)
  var col int = len(matrix[0])
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // This loop is iterating cols
    for j := 0 ; j < col ; j++ {
      fmt.Print("  ", matrix[i][j])
    }
    // Add new line
    fmt.Print("\n")
  }
  // Add new line
  fmt.Print("\n")
}
// Count sorted rows in given matrix
func(this Test) sortedRows(matrix[][] int) {
  // Get size
  var row int = len(matrix)
  var col int = len(matrix[0])
  // Resulant counter
  var result int = 0
  // This loop is iterating rows
  for i := 0 ; i < row ; i++ {
    // If flag equal to 1 then work on decreasing order 
    // Otherwise work on increasing order 
    // Check first and last element of i row
    var flag bool = matrix[i][0] > matrix[i][col - 1]
    // Assume that is  a sorted row
    result++
    // Check if row is sorted or not
    for j := 1 ; j < col ; j++ {
      if flag == true && matrix[i][j - 1] < matrix[i][j] {
        // is not sorted
        result--
        break
      } else if flag == false && matrix[i][j - 1] > matrix[i][j] {
        // is not sorted
        result--
        break
      }
    }
  }
  // Display calculated result
  fmt.Println(" Sorted Rows : ", result)
}
func main() {
  var task * Test = getTest()
  // Matrix of integer elements
  var matrix = [][] int {
    {1 , 2 , 3 , 4 , 5 , 6},
    {4 , 8 , 7 , 8 , 5 , 1},
    {9 , 8 , 7 , 7 , 5 , 1},
    {7 , 7 , 6 , 5 , 4 , 1},
    {7 , 3 , 2 , 5 , 1 , 1},
    {5 , 5 , 5 , 5 , 5 , 5},
  }
  task.showData(matrix)
  task.sortedRows(matrix)
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
// Include namespace system
using System;
/*
  Csharp Program
  Count all sorted rows in a matrix
*/
public class Test
{
    // Display element of matrix
    public void showData(int[,] matrix)
    {
        int row = matrix.GetLength(0);
        int col = matrix.GetLength(1);
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // This loop is iterating cols
            for (int j = 0; j < col; ++j)
            {
                Console.Write("  " + matrix[i,j]);
            }
            // Add new line
            Console.Write("\n");
        }
        // Add new line
        Console.Write("\n");
    }
    // Count sorted rows in given matrix
    public void sortedRows(int[,] matrix)
    {
        // Get size
        int row = matrix.GetLength(0);
        int col = matrix.GetLength(1);
        // Resulant counter
        int result = 0;
        // This loop is iterating rows
        for (int i = 0; i < row; ++i)
        {
            // If flag equal to 1 then work on decreasing order 
            // Otherwise work on increasing order 
            // Check first and last element of i row
            Boolean flag = matrix[i,0] > matrix[i,col - 1];
            // Assume that is  a sorted row
            result++;
            // Check if row is sorted or not
            for (int j = 1; j < col; ++j)
            {
                if (flag == true && matrix[i,j - 1] < matrix[i,j])
                {
                    // is not sorted
                    result--;
                    break;
                }
                else if (flag == false && matrix[i,j - 1] > matrix[i,j])
                {
                    // is not sorted
                    result--;
                    break;
                }
            }
        }
        // Display calculated result
        Console.WriteLine(" Sorted Rows : " + result);
    }
    public static void Main(String[] args)
    {
        Test task = new Test();
        // Matrix of integer elements
        int[,] matrix = {
            {1 , 2 , 3 , 4 , 5 , 6},
            {4 , 8 , 7 , 8 , 5 , 1},
            {9 , 8 , 7 , 7 , 5 , 1},
            {7 , 7 , 6 , 5 , 4 , 1},
            {7 , 3 , 2 , 5 , 1 , 1},
            {5 , 5 , 5 , 5 , 5 , 5}
        };
        task.showData(matrix);
        task.sortedRows(matrix);
    }
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
<?php
/*
  Php Program
  Count all sorted rows in a matrix
*/
class Test
{
  // Display element of matrix
  public  function showData($matrix)
  {
    $row = count($matrix);
    $col = count($matrix[0]);
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // This loop is iterating cols
      for ($j = 0; $j < $col; ++$j)
      {
        echo("  ".$matrix[$i][$j]);
      }
      // Add new line
      echo("\n");
    }
    // Add new line
    echo("\n");
  }
  // Count sorted rows in given matrix
  public  function sortedRows($matrix)
  {
    // Get size
    $row = count($matrix);
    $col = count($matrix[0]);
    // Resulant counter
    $result = 0;
    // This loop is iterating rows
    for ($i = 0; $i < $row; ++$i)
    {
      // If flag equal to 1 then work on decreasing order 
      // Otherwise work on increasing order 
      // Check first and last element of i row
      $flag = $matrix[$i][0] > $matrix[$i][$col - 1];
      // Assume that is  a sorted row
      $result++;
      // Check if row is sorted or not
      for ($j = 1; $j < $col; ++$j)
      {
        if ($flag == true && 
                    $matrix[$i][$j - 1] < $matrix[$i][$j])
        {
          // is not sorted
          $result--;
          break;
        }
        else if ($flag == false && 
                         $matrix[$i][$j - 1] > $matrix[$i][$j])
        {
          // is not sorted
          $result--;
          break;
        }
      }
    }
    // Display calculated result
    echo(" Sorted Rows : ".$result."\n");
  }
}

function main()
{
  $task = new Test();
  // Matrix of integer elements
  $matrix = array(
      array(1, 2, 3, 4, 5, 6), 
      array(4, 8, 7, 8, 5, 1), 
      array(9, 8, 7, 7, 5, 1), 
      array(7, 7, 6, 5, 4, 1), 
      array(7, 3, 2, 5, 1, 1), 
      array(5, 5, 5, 5, 5, 5)
    );
  $task->showData($matrix);
  $task->sortedRows($matrix);
}
main();

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
/*
  Node JS Program
  Count all sorted rows in a matrix
*/
class Test
{
  // Display element of matrix
  showData(matrix)
  {
    var row = matrix.length;
    var col = matrix[0].length;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // This loop is iterating cols
      for (var j = 0; j < col; ++j)
      {
        process.stdout.write("  " + matrix[i][j]);
      }
      // Add new line
      process.stdout.write("\n");
    }
    // Add new line
    process.stdout.write("\n");
  }
  // Count sorted rows in given matrix
  sortedRows(matrix)
  {
    // Get size
    var row = matrix.length;
    var col = matrix[0].length;
    // Resulant counter
    var result = 0;
    // This loop is iterating rows
    for (var i = 0; i < row; ++i)
    {
      // If flag equal to 1 then work on decreasing order 
      // Otherwise work on increasing order 
      // Check first and last element of i row
      var flag = matrix[i][0] > matrix[i][col - 1];
      // Assume that is  a sorted row
      result++;
      // Check if row is sorted or not
      for (var j = 1; j < col; ++j)
      {
        if (flag == true && 
                    matrix[i][j - 1] < matrix[i][j])
        {
          // is not sorted
          result--;
          break;
        }
        else if (flag == false && 
                         matrix[i][j - 1] > matrix[i][j])
        {
          // is not sorted
          result--;
          break;
        }
      }
    }
    // Display calculated result
    console.log(" Sorted Rows : " + result);
  }
}

function main()
{
  var task = new Test();
  // Matrix of integer elements
  var matrix = [
    [1, 2, 3, 4, 5, 6],
    [4, 8, 7, 8, 5, 1],
    [9, 8, 7, 7, 5, 1],
    [7, 7, 6, 5, 4, 1],
    [7, 3, 2, 5, 1, 1],
    [5, 5, 5, 5, 5, 5]
  ];
  task.showData(matrix);
  task.sortedRows(matrix);
}
main();

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
#  Python 3 Program
#  Count all sorted rows in a matrix
class Test :
  #  Display element of matrix
  def showData(self, matrix) :
    row = len(matrix)
    col = len(matrix[0])
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      j = 0
      #  This loop is iterating cols
      while (j < col) :
        print("  ", matrix[i][j], end = "")
        j += 1
      
      #  Add new line
      print(end = "\n")
      i += 1
    
    #  Add new line
    print(end = "\n")
  
  #  Count sorted rows in given matrix
  def sortedRows(self, matrix) :
    #  Get size
    row = len(matrix)
    col = len(matrix[0])
    #  Resulant counter
    result = 0
    i = 0
    #  This loop is iterating rows
    while (i < row) :
      #  If flag equal to 1 then work on decreasing order 
      #  Otherwise work on increasing order 
      #  Check first and last element of i row
      flag = matrix[i][0] > matrix[i][col - 1]
      #  Assume that is  a sorted row
      result += 1
      j = 1
      #  Check if row is sorted or not
      while (j < col) :
        if (flag == True and matrix[i][j - 1] < matrix[i][j]) :
          #  is not sorted
          result -= 1
          break
        elif (flag == False and matrix[i][j - 1] > matrix[i][j]) :
          #  is not sorted
          result -= 1
          break
        
        j += 1
      
      i += 1
    
    #  Display calculated result
    print(" Sorted Rows : ", result)
  

def main() :
  task = Test()
  #  Matrix of integer elements
  matrix = [
    [1, 2, 3, 4, 5, 6],
    [4, 8, 7, 8, 5, 1],
    [9, 8, 7, 7, 5, 1],
    [7, 7, 6, 5, 4, 1],
    [7, 3, 2, 5, 1, 1],
    [5, 5, 5, 5, 5, 5]
  ]
  task.showData(matrix)
  task.sortedRows(matrix)

if __name__ == "__main__": main()

Output

   1   2   3   4   5   6
   4   8   7   8   5   1
   9   8   7   7   5   1
   7   7   6   5   4   1
   7   3   2   5   1   1
   5   5   5   5   5   5

 Sorted Rows :  4
#  Ruby Program
#  Count all sorted rows in a matrix
class Test 
  #  Display element of matrix
  def showData(matrix) 
    row = matrix.length
    col = matrix[0].length
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      j = 0
      #  This loop is iterating cols
      while (j < col) 
        print("  ", matrix[i][j])
        j += 1
      end

      #  Add new line
      print("\n")
      i += 1
    end

    #  Add new line
    print("\n")
  end

  #  Count sorted rows in given matrix
  def sortedRows(matrix) 
    #  Get size
    row = matrix.length
    col = matrix[0].length
    #  Resulant counter
    result = 0
    i = 0
    #  This loop is iterating rows
    while (i < row) 
      #  If flag equal to 1 then work on decreasing order 
      #  Otherwise work on increasing order 
      #  Check first and last element of i row
      flag = matrix[i][0] > matrix[i][col - 1]
      #  Assume that is  a sorted row
      result += 1
      j = 1
      #  Check if row is sorted or not
      while (j < col) 
        if (flag == true && matrix[i][j - 1] < matrix[i][j]) 
          #  is not sorted
          result -= 1
          break
        elsif (flag == false && matrix[i][j - 1] > matrix[i][j]) 
          #  is not sorted
          result -= 1
          break
        end

        j += 1
      end

      i += 1
    end

    #  Display calculated result
    print(" Sorted Rows : ", result, "\n")
  end

end

def main() 
  task = Test.new()
  #  Matrix of integer elements
  matrix = [
    [1, 2, 3, 4, 5, 6],
    [4, 8, 7, 8, 5, 1],
    [9, 8, 7, 7, 5, 1],
    [7, 7, 6, 5, 4, 1],
    [7, 3, 2, 5, 1, 1],
    [5, 5, 5, 5, 5, 5]
  ]
  task.showData(matrix)
  task.sortedRows(matrix)
end

main()

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
/*
  Scala Program
  Count all sorted rows in a matrix
*/
import scala.util.control._
class Test()
{
  // Display element of matrix
  def showData(matrix: Array[Array[Int]]): Unit = {
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        print("  " + matrix(i)(j));
        j += 1;
      }
      // Add new line
      print("\n");
      i += 1;
    }
    // Add new line
    print("\n");
  }
  // Count sorted rows in given matrix
  def sortedRows(matrix: Array[Array[Int]]): Unit = {
    // Get size
    var row: Int = matrix.length;
    var col: Int = matrix(0).length;
    // Resulant counter
    var result: Int = 0;
    var i: Int = 0;
    val breakLoop = new Breaks;
    // This loop is iterating rows
    while (i < row)
    {
      // If flag equal to 1 then work on decreasing order 
      // Otherwise work on increasing order 
      // Check first and last element of i row
      var flag: Boolean = matrix(i)(0) > matrix(i)(col - 1);
      // Assume that is  a sorted row
      result += 1;
      var j: Int = 1;
      breakLoop.breakable
      {
        // Check if row is sorted or not
        while (j < col)
        {
          if (flag == true && matrix(i)(j - 1) < matrix(i)(j))
          {
            // is not sorted
            result -= 1;
            breakLoop.break;
          }
          else if (flag == false && matrix(i)(j - 1) > matrix(i)(j))
          {
            // is not sorted
            result -= 1;
            breakLoop.break;
          }
          j += 1;
        }
      }
      i += 1;
    }
    // Display calculated result
    println(" Sorted Rows : " + result);
  }
}
object Main
{
  def main(args: Array[String]): Unit = {
    var task: Test = new Test();
    // Matrix of integer elements
    var matrix: Array[Array[Int]] = Array(
          Array(1, 2, 3, 4, 5, 6), 
          Array(4, 8, 7, 8, 5, 1), 
          Array(9, 8, 7, 7, 5, 1), 
          Array(7, 7, 6, 5, 4, 1), 
          Array(7, 3, 2, 5, 1, 1), 
          Array(5, 5, 5, 5, 5, 5)
        );
    task.showData(matrix);
    task.sortedRows(matrix);
  }
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4
import Foundation;
/*
  Swift 4 Program
  Count all sorted rows in a matrix
*/
class Test
{
  // Display element of matrix
  func showData(_ matrix: [[Int]])
  {
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        print("  ", matrix[i][j], terminator: "");
        j += 1;
      }
      // Add new line
      print(terminator: "\n");
      i += 1;
    }
    // Add new line
    print(terminator: "\n");
  }
  // Count sorted rows in given matrix
  func sortedRows(_ matrix: [
    [Int]
  ])
  {
    // Get size
    let row: Int = matrix.count;
    let col: Int = matrix[0].count;
    // Resulant counter
    var result: Int = 0;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      // If flag equal to 1 then work on decreasing order 
      // Otherwise work on increasing order 
      // Check first and last element of i row
      let flag: Bool = matrix[i][0] > matrix[i][col - 1];
      // Assume that is  a sorted row
      result += 1;
      var j: Int = 1;
      // Check if row is sorted or not
      while (j < col)
      {
        if (flag == true && matrix[i][j - 1] < matrix[i][j])
        {
          // is not sorted
          result -= 1;
          break;
        }
        else if (flag == false && matrix[i][j - 1] > matrix[i][j])
        {
          // is not sorted
          result -= 1;
          break;
        }
        j += 1;
      }
      i += 1;
    }
    // Display calculated result
    print(" Sorted Rows : ", result);
  }
}
func main()
{
  let task: Test = Test();
  // Matrix of integer elements
  let matrix: [
    [Int]
  ] = [
    [1, 2, 3, 4, 5, 6],
    [4, 8, 7, 8, 5, 1],
    [9, 8, 7, 7, 5, 1],
    [7, 7, 6, 5, 4, 1],
    [7, 3, 2, 5, 1, 1],
    [5, 5, 5, 5, 5, 5]
  ];
  task.showData(matrix);
  task.sortedRows(matrix);
}
main();

Output

   1   2   3   4   5   6
   4   8   7   8   5   1
   9   8   7   7   5   1
   7   7   6   5   4   1
   7   3   2   5   1   1
   5   5   5   5   5   5

 Sorted Rows :  4
/*
  Kotlin Program
  Count all sorted rows in a matrix
*/
class Test
{
  // Display element of matrix
  fun showData(matrix: Array < Array < Int >> ): Unit
  {
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      var j: Int = 0;
      // This loop is iterating cols
      while (j < col)
      {
        print("  " + matrix[i][j]);
        j += 1;
      }
      // Add new line
      print("\n");
      i += 1;
    }
    // Add new line
    print("\n");
  }
  // Count sorted rows in given matrix
  fun sortedRows(matrix: Array < Array < Int >> ): Unit
  {
    // Get size
    val row: Int = matrix.count();
    val col: Int = matrix[0].count();
    // Resulant counter
    var result: Int = 0;
    var i: Int = 0;
    // This loop is iterating rows
    while (i < row)
    {
      // If flag equal to 1 then work on decreasing order 
      // Otherwise work on increasing order 
      // Check first and last element of i row
      val flag: Boolean = matrix[i][0] > matrix[i][col - 1];
      // Assume that is  a sorted row
      result += 1;
      var j: Int = 1;
      // Check if row is sorted or not
      while (j < col)
      {
        if (flag == true && matrix[i][j - 1] < matrix[i][j])
        {
          // is not sorted
          result -= 1;
          break;
        }
        else if (flag == false && matrix[i][j - 1] > matrix[i][j])
        {
          // is not sorted
          result -= 1;
          break;
        }
        j += 1;
      }
      i += 1;
    }
    // Display calculated result
    println(" Sorted Rows : " + result);
  }
}
fun main(args: Array < String > ): Unit
{
  val task: Test = Test();
  // Matrix of integer elements
  val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(1, 2, 3, 4, 5, 6), 
      arrayOf(4, 8, 7, 8, 5, 1), 
      arrayOf(9, 8, 7, 7, 5, 1), 
      arrayOf(7, 7, 6, 5, 4, 1), 
      arrayOf(7, 3, 2, 5, 1, 1), 
      arrayOf(5, 5, 5, 5, 5, 5)
    );
  task.showData(matrix);
  task.sortedRows(matrix);
}

Output

  1  2  3  4  5  6
  4  8  7  8  5  1
  9  8  7  7  5  1
  7  7  6  5  4  1
  7  3  2  5  1  1
  5  5  5  5  5  5

 Sorted Rows : 4

Output Explanation

The given matrix is displayed, and the output indicates the count of sorted rows. In this case, there are four rows (first, third, fourth, and fifth) that are sorted either in increasing or decreasing order, and the output reflects this count as 4.

Time Complexity

The time complexity of this algorithm is O(rows * cols), where rows is the number of rows in the matrix and cols is the number of columns in the matrix. This is because we iterate through each element of each row once in a nested loop structure.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment