CC-16 : Generate horizontal mirror image of matrix.
Description:
Description A mirror image of matrix is formed when the position of elements is horizontally inverted. Given an input matrix mat, generate and return the horizontal mirror image of the same.
Test cases and expected outputs:
| Input | Expected outputs |
|---|---|
| mat = { {0,1,2}, {3,4,5}, {6,7,8}} |
2,1,0, 5,4,3, 8,7,6, |
| mat = { {0,1,2,3}, {0,1,2,3}, {0,1,2,3},}; |
3,2,1,0, 3,2,1,0, 3,2,1,0, |
| mat = { {9,10}, {9,10}, {9,10}, {9,10}}; |
10,9, 10,9, 10,9, 10,9, |
Pseudocode:
| The java method should accept following input parameters: mat (integer matrix). |
| To create mirror image, we need to replace elements at column 0 with elements at column mat[0].length-1, also replace elements at column 1 with elements at column mat[0].length-2 and so on. Note: This replacement has to be done to indexes less than mat[0].length/2 only. In the next points let’s see how this will be done. |
| Declare a variable temp, which will be used to hold temporary values while we exchange elements at 2 positions in the 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/2. Notice that we will iterate only till mat[0].length/2.:
Interchange the values at mat[rIdx][cIdx] and mat[rIdx][mat[0].length-1-cIdx]; using the temp variable.
|
| Once above loops complete, mat now contains the horizontal mirror image of the input matrix. Return mat. |
Code:
public int[][] matMirrorImageHorizontal(int[][] mat) throws Exception{
int temp;
for (int cIdx=0; cIdx < mat[0].length/2; cIdx++) {
for (int rIdx=0; rIdx < mat.length; rIdx++) {
temp=mat[rIdx][cIdx];
mat[rIdx][cIdx]=mat[rIdx][mat[0].length-1-cIdx];
mat[rIdx][mat[0].length-1-cIdx]=temp;
}
}
return mat;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |