Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.

I need to pass an array to a method and inside of that method I need to swap the rows around so if it's

1 2 3

3 2 1

2 1 3

it needs to be

3 2 1

1 2 3

3 1 2

With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.

3 1 2

1 3 2

3 2 1

Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.

Here is the code I have right now that's sort of working

public static void reverseRows(int[][] inTwoDArray)
{
   for (int row = 0; row < inTwoDArray.length; row++)
   {
       for (int col = 0; col < inTwoDArray[row].length; col++)
       {
           int tempHolder = inTwoDArray[row][col];
           inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
           inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
       }
    }
 }

any help would be great, I'm running out of hair to pull out! Thanks!

like image 260
iHeff Avatar asked Nov 18 '25 22:11

iHeff


1 Answers

First, how to reverse a single 1-D array:

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

Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).

Then put it in another for loop:

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

Another approach would be to use some library method such as from ArrayUtils#reverse():

ArrayUtils.reverse(array);

And then again put into a cycle:

for(int i = 0; i < array.length; i++){
   ArrayUtils.reverse(array[i]);
}
like image 116
Kuba Spatny Avatar answered Nov 20 '25 11:11

Kuba Spatny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!