0

I have a 2D array that I would like to flip clockwise (no, this is not a homework assignment!). I have the following output as my code tries to flip the array by creating a new temporary one.

// Original array
I/System.out: 10 11 12 13 14 
I/System.out: 15 16 17 18 19 

// Temp array
I/System.out: 10 15 
I/System.out: 11 16 
I/System.out: 12 17 
I/System.out: 13 18 
I/System.out: 14 19 

What I want is for the second array (15 - 19) to be in the first column. I just do not understand what I am doing wrong.

The code is as follows:

Object[][][] containerTemp = new Object[zDim][yDim][xDim];
for (int z = 0; z < zDim; z++) {
   for (int y = yDim - 1; y >= 0; y--) {
      for (int x = 0; x < xDim; x++) {
         containerTemp[z][y][x] = container[z][x][y];
      }
   }
}

The final result of the Temp array will be correct for the purpose of the project, but I have other code that will do this part, I just want these nested for loops to "flip" the array without moving the values.

5
  • 1
    You seem to be using "flip" and "rotate" interchangeably, but they aren't the same thing. Commented Jan 3, 2018 at 20:27
  • 1
    Debuggers are quite helpful in determining why code is working a certain way. Pen and paper would probably be just as useful in this case. Commented Jan 3, 2018 at 20:28
  • You're doing what I'd call Transposition there. Commented Jan 3, 2018 at 20:44
  • @azurefrog : Yes, sorry about that! I ment flip. You could think about it like a bookcase that is faced down. I would like to make it stand without the items in it changing. Commented Jan 3, 2018 at 20:59
  • @ Jonny Henly : Sometimes, yes. It did not help me this time. @AndyTurner : Yes, I didn't know what thing existed until today. But that is what I am trying to do as my earlier solution actually moved values around in the matrix. Commented Jan 3, 2018 at 21:06

1 Answer 1

1

Try with:

Object[][][] containerTemp = new Object[zDim][yDim][xDim];
for (int z = 0; z < zDim; z++) {
   for (int y = yDim - 1; y >= 0; y--) {
      for (int x = 0; x < xDim; x++) {
         containerTemp[z][y][xDim - (x + 1)] = container[z][x][y]; // change x target.
      }
   }

}

Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Thank you! Could you explain the difference between what I wrote and what changes you made to make it work?! Thank you!
@goldenmaza I added a step after traspose: It flips horizontally ('x' coordinate).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.