Solution Review: Mirror a 2D Array
Have a look at the solution to the 'Mirror a 2D array' challenge.
We'll cover the following...
Rubric criteria
Solution
Press + to interact
class MirrorImage{public static void main(String args[]){int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};int[][] result = new int[array.length][array[0].length];result = mirror(array); // Calling the method// Printing the mirror imagefor(int i = 0; i < result.length; i++){for(int j = 0; j < result[i].length; j++){System.out.print(result[i][j]);System.out.print(" ");}System.out.print("\n");}}// Method to mirror the 2D arraypublic static int[][] mirror(int[][] origArray){int[][] array = new int[origArray.length][origArray[0].length]; // Creating new array to avoid overriding// Copying the elementsfor(int i = 0; i < array.length; i++){for(int j = 0; j < array[i].length; j++){array[i][j] = origArray[i][j];}}for( int i = 0; i < array.length; i++ ) // Moving row-wise{for( int j = 0; j < (array[i].length)/2; j++) // Moving upto the middle - columnn-wise in a row{if(j != array[i].length-1-j) // Swapping the columns' values{int temp = array[i][j];array[i][j] = array[i][array[i].length-1-j];array[i][array[i].length-1-j] = temp;}}}return array;}}
Rubric-wise explanation
Point 1:
Look at line 23. We have the header of the mirror
function. It takes an integer 2D array (int[][]
) as a parameter and also returns an integer 2D array (int[][]
).
Point 2:
In lines 28-34, we create a copy of the origArray
(argument to the method) because we don’t want to change it.
❌ Note: We can’t do
array = origArray
. Because this statement will makearray
point toorigArray
. So, any ...