CC-8 : Count negative elements in a matrix.
Description:
Given input matrix mat, where each row of matrix is individually sorted incrementally, we need to traverse it and count the elements that are negative.
Test cases and expected outputs:
| Input | Expected outputs |
|---|---|
| mat = { {-2,-1,5,6}, {0,3,5,7}, {-4,-3,-2,-1}} |
Matrix has 6 negative numbers. |
| mat= { {-4,1,5,6}, {-6,-3,0,16}, {-9,-6,-3,0} } |
Matrix has 6 negative numbers. |
Pseudocode:
| The java method should accept following input parameters: mat (integer matrix). |
| Initialize a variable nCnt to hold the count of negative numbers found in mat. |
| Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If mat[rIdx][cIdx] is negative, increment nCnt by 1.
If mat[rIdx][cIdx] is 0 or positive, exit the inner loop. This is because the rows are sorted, so once we find 0 or positive number, then we will not find any further negative numbers in that row.
|
| • Once above loops are completed, return nCnt. |
Code:
public int matArrayCountNegatives(int[][] mat) throws Exception{
int nCnt=0;
for (int rIdx=0; rIdx < mat.length; rIdx++) {
for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
if (mat[rIdx][cIdx] < 0 ) {
nCnt++;
}else {
break;
}
}
}
return nCnt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |