U5L4 Extra Practice - Reversing Rows and Columns of a 2D Array

In the free response section of U5L4 Extra practice, the following prompt is given:

Do This: Write a reverse method that modifies the parameter instead of returning a new 2D array. For example, if arr contains {{1, 2, 3}, {4, 5, 6}}, then after executing reverse(arr), arr should contain {{6, 5, 4}, {3, 2, 1}}.

The answer key provides the following answer:

public static void reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
for (int j = 0; j < arr[0].length; j++) {
int temp = arr[i][j];
arr[i][j] = arr[arr.length - i - 1][arr[0].length - j - 1];
arr[arr.length - i - 1][arr[0].length - j - 1] = temp;
}
}
}

Our class pointed out that as written, the code will NOT reach the middle row of any array with an ODD number of rows. Coding this in Java Lab confirms the issue. In other words, the middle “inner” array (or horizontal array) does not get reversed.

Our question is: what is the correct code? Do you have to create a conditional, with one algorithm for “even” arrays and one for “odd”?

Thank you!

Hello @nlsmith,
I’m not quite sure what you mean? this example should work in both cases

public class ArrayReverse {
    public static int[][] reverse(int[][] arr) {
        for (int i = 0; i < arr.length / 2; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                int temp = arr[i][j];
                arr[i][j] = arr[arr.length - i - 1][arr[0].length - j - 1];
                arr[arr.length - i - 1][arr[0].length - j - 1] = temp;
            }
        }
        return arr;
    }
    public static void main(String[] args) {
        int[][] array2D = {{1,2,3}, {4,5,6}, {7,8,9}};
        int[][] flipped2D = reverse(array2D);
        for(int i = 0; i < flipped2D.length; i++) {
            for(int j = 0; j < flipped2D[i].length; j++) {
                System.out.printf("%d", flipped2D[i][j]);
            }
            System.out.print("\n");
        }
    }
}

for me this solution works perfectly weather it’s even or odd, would you mind elaborating?

I am seeing the issue you and your class found, @nlsmith -
The middle array is not reversed when there is an odd number of rows. I made the two versions to attempt to reverse an array at this link to investigate this issue.
The method I called reverseFirstWay goes through the entire array and reverses it including the middle row if the number of rows is odd. Looking at the output in the console you can see that the 4,5,6 became 6,5,4
The method I called reverseSecondWay is what was on the activity guide that does not hit the middle row when the number of rows is odd-- the 4,5,6 is not reversed.
Best,
Lindsay

1 Like