CC-19 :Reshape matrix as per input rows and columns.
Description:
Given input int matrix mat, reshape it into a new matrix as per required rows and columns.
Test cases and expected outputs:
| Input | Expected outputs |
|---|---|
| reqRows=1, reqCols=9 mat = { {0,1,2}, {3,4,5}, {6,7,8}}; |
Reshaped Matrix 1x9: 0,1,2,3,4,5,6,7,8, |
| reqRows=2, reqCols=4 mat = { {1,2}, {3,4}, {5,6}, {7,8}}; |
Reshaped Matrix 2x4: 1,2,3,4, 5,6,7,8, |
| reqRows=6, reqCols=2 mat = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}}; |
Reshaped Matrix 6x2: 1,2, 3,4, 5,6, 7,8, 9,10, 11,12, |
Pseudocode:
| The java method should accept following input parameters: mat (int square matrix), int reqRows, int reqCols. |
| If number of elements in mat not equal to reqRows*reqCols; then return null as the input matrix cannot be reshaped as per requirements. |
| Declare an int matrix nMatrix of size reqRows * reqCols to hold the reshaped matrix. |
| Initialize 2 int variables newrIdx=0 and newcIdx=0; these variable will hold indexes of new reshaped matrix. |
| 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:
Set nMatrix[newrIdx][newcIdx]= mat[rIdx][cIdx].
Increment newcIdx by 1.
Check if (newcIdx>= reqCols) if so we need to move to next row of nMatrix:
newcIdx=0;
newrIdx++;
|
| After above loops are completed, mat has been reshaped to nMatrix with required rows and columns. Return nMatrix. |
Code:
public int[][] matReshape(int[][] mat, int reqRows, int reqCols) throws Exception{
if ((mat.length*mat[0].length) != (reqRows*reqCols)) { return null;}
int[][] nMatrix=new int[reqRows][reqCols];
int newrIdx=0; int newcIdx=0;
for (int rIdx=0; rIdx < mat.length; rIdx++) {
for (int cIdx=0; cIdx< mat[0].length; cIdx++) {
nMatrix[newrIdx][newcIdx]= mat[rIdx][cIdx];
newcIdx++;
if (newcIdx>= reqCols) {
newcIdx=0;
newrIdx++;
}
}
}
return nMatrix;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |