Learn-dsa..in 30 days!



























CC-14 : Return lower triangle elements of matrix.

Description:

Lower triangle elements are the elements at indexes below the diagonal indexes of the matrix. Given input matrix mat, return the elements that are part of the lower triangle of the matrix.

Test cases and expected outputs:

Input Expected outputs
mat = {
{1,2,3},
{4,5,6},
{7,8,9}};
Lower Triangle elements: 4,7,8.
mat = {
{55,66,77,88},
{11,22,33,44},
{99,109,119,129},
{44,66,11,22}};
Lower Triangle elements: 11,99,109,44,66,11.
mat = {
{30,40},
{50,60}, };
Lower Triangle element: 50.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize an int variable n and set it to count of rows of mat.
Initialize an int array named triangleElements with length (n*(n-1))/2.
Initialize an int variable tIdx=0 to hold the index value of triangleElements array.
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 (rIdx > cIdx), then set triangleElements[tIdx]=mat[rIdx][cIdx].
Increment tIdx by 1.
At the end of above loop, return the triangleElements array with the lower triangle elements.

Code:

public int[]  matLowerTriangle(int[][] mat) throws Exception{
	int n=mat.length; int tIdx=0;
	int[] triangleElements=new int[(n*(n-1))/2];
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
			if (rIdx > cIdx) {
				triangleElements[tIdx]=mat[rIdx][cIdx];
				tIdx++;
			}
		}
	}
	return triangleElements;
}

Click here to download and run code and test cases !