Home > front end >  Reverse 2d array rows
Reverse 2d array rows

Time:10-15

I've got 2d array:

int firstDimension = data.length / 8;
int secondDimension = 8;
int[][] arr = new int[firstDimension][secondDimension];

[[1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0]]
   

I need to reversse array rows and get:

[[1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]

I found algorithm to reverse 1d array elements:

   for (int i = 0; i < validData.length / 2; i  ) {
            int temp = validData[i];
            validData[i] = validData[validData.length - i - 1];
            validData[validData.length - i - 1] = temp;
        }

How can I reverse array rows?

CodePudding user response:

There are multiple ways to do that but i'll suggest you to use the Collections#reverse method which is used to reverse the order of the elements in the specified list. In your case, each element is an array, so the main array will reverse the elements (arrays).

import java.util.Collections
Collections.reverse(Arrays.asList(arr));

CodePudding user response:

Work for me:

 for (int j = 0; j < arr.length / 2; j  ) {
        int[] temp = arr[j];
        arr[j] = arr[arr.length - j - 1];
        arr[arr.length - j - 1] = temp;
    }

CodePudding user response:

    int[][] arr = {{1, 1, 1, 1, 1, 1,1, 1}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 1}, {1, 0, 1, 0, 1, 0, 1, 0}};
    
    //assuming all arrays in arr have same length!
    int[][] arr2 = new int [arr.length][arr[0].length];         
    int k = arr2.length-1;
    
    //copy in reverse order
    for (int i = 0; i < arr.length; i  ) {          
        for (int j = 0; j < arr[i].length; j  ) {
            int temp = arr[i][j];
            arr2[k][j] = temp;
        }
        k--;
    }
    
    //print arr2
    for (int i = 0; i < arr2.length; i  ) {
        System.out.print("{");
        for (int j = 0; j < arr2[i].length; j  ) {
            System.out.print(arr2[i][j]);
        }
        System.out.print("}");
    }

This solution only works if all Arrays in arr have same length

  • Related