javaarraysreverseflipinversion

Inverting a two-dimensional array


I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not. Can't find a mistake right here:

public int[][] flipAndInvert(int[][] A) {
    int row = -1;
    int col = -1;
    int[][] arr = A;

    for (int i = 0; i < arr.length; i++) {
        row++;
        col = -1;
        for (int j = arr[i].length - 1; j >= 0; j--) {
            col++;
            arr[row][col] = A[i][j];
        }
    }
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            if (arr[i][j] == 1) {
                arr[i][j] = 0;
            } else {
                arr[i][j] = 1;
            }
        }
    }
    return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };

After proceeding the output should be: After inverting: {1,1,0},{1,0,0},{0,0,0} After flipping: {0,0,1,},{0,1,1},{1,1,1}

Thanks to all a lot, the problem was here: int[][] arr = A; The reference of the array is being passed to arr.


Solution

  • What I think is that since you are using this line:

    int[][] arr = A;
    

    The reference of the array is being passed to arr, and hence the line:

    arr[row][col] = A[i][j];
    

    is equivalent to:

    A[row][col] = A[i][j];
    

    as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)

    You can fix this by either using the new keyword with arr and then initializing it:

    int[][] arr = new int[someRows][someCols];
    //use for loop to assign the value to each element of arr
    

    Or you can run the for loop till arr[i].length/2 - 1:

        for (int i = 0; i < arr.length; i++) {
        row++;
        col = -1;
        for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
            col++; 
            arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
        }
    }