Count all the columns in a matrix which are sorted in descending
Last Updated :
14 Apr, 2023
Given a matrix mat[][], the task is to count the number of columns that are sorted in descending.
Examples:
Input: mat[][] = {{1, 3}, {0, 2}}
Output: 2 First column: 1 > 0 Second column: 3 > 2 Hence, the count is 2
Input: mat[][] = {{2, 2}, {1, 3}}
Output: 1
Approach:
Traverse each column one by one and check if the next element ? previous element in the same column. If the condition is valid for all the possible elements then increment the count by 1. After all the columns have been traversed, print the count.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
int countDescCol(vector<vector< int >> A) {
int countOfCol = 0;
for ( int j = 0; j < A[0].size(); j++) {
bool isDescending = true ;
for ( int i = 0; i < A.size() - 1; i++) {
if (A[i][j] < A[i + 1][j]) {
isDescending = false ;
break ;
}
}
if (isDescending) {
countOfCol++;
}
}
return countOfCol;
}
int main() {
vector<vector< int >> A = {{1, 3}, {0, 2}};
cout << countDescCol(A) << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static int countDescCol(List<List<Integer>> A) {
int countOfCol = 0 ;
for ( int j = 0 ; j < A.get( 0 ).size(); j++) {
boolean isDescending = true ;
for ( int i = 0 ; i < A.size() - 1 ; i++) {
if (A.get(i).get(j) < A.get(i + 1 ).get(j)) {
isDescending = false ;
break ;
}
}
if (isDescending) {
countOfCol++;
}
}
return countOfCol;
}
public static void main(String[] args) {
List<List<Integer>> A = new ArrayList<>();
A.add( new ArrayList<Integer>() {{
add( 1 );
add( 3 );
}});
A.add( new ArrayList<Integer>() {{
add( 0 );
add( 2 );
}});
System.out.println(countDescCol(A));
}
}
|
Python3
def countDescCol(A):
countOfCol = 0
for col in zip ( * A):
if all (col[i] > = col[i + 1 ] for i in range ( len (col) - 1 )):
countOfCol + = 1
return countOfCol
A = [[ 1 , 3 ], [ 0 , 2 ]]
print (countDescCol(A))
|
C#
using System;
using System.Collections.Generic;
public class MainClass {
public static int countDescCol(List<List< int >> A) {
int countOfCol = 0;
for ( int j = 0; j < A[0].Count; j++) {
bool isDescending = true ;
for ( int i = 0; i < A.Count - 1; i++) {
if (A[i][j] < A[i + 1][j]) {
isDescending = false ;
break ;
}
}
if (isDescending) {
countOfCol++;
}
}
return countOfCol;
}
public static void Main() {
List<List< int >> A = new List<List< int >>();
A.Add( new List< int > {1, 3});
A.Add( new List< int > {0, 2});
Console.WriteLine(countDescCol(A));
}
}
|
Javascript
function countDescCol(A) {
let countOfCol = 0;
A[0].map((_, colIndex) => A.map(row => row[colIndex])).forEach(col => {
if (col.slice(1).every((item, i) => col[i] >= item)) {
countOfCol += 1;
}
});
return countOfCol;
}
let A = [[1, 3], [0, 2]];
console.log(countDescCol(A));
|
Share your thoughts in the comments
Please Login to comment...