I'm experimenting with two different methods to get a bidimensional array to rotate. Both work when inheritance isn't involved, but as soon as I extend the class, one of them gives weird results.
This is the one that always works:
- Make a new, empty array of the same size as the one that I want to rotate.
- Copy the cells from the original array into this new array in a different order to imitate rotation - so, say, if I'm rotating the array anti-clockise, the cell that's in the upper-right corner [0][2] would go in the upper left corner [0][0] (this can and will be improved with for cycles instead, of course).
- Once it's all filled, copy the new array into the original array.
This is what doesn't work:
- Copy the bidimensional array.
- Take single cells from this new array I just filled and put them back into the original array, but in a different order - (as explained in step 2 above).
However, the results I get from this latter one indicate that it's like the copy array it's initialized everytime a new line in executes, so the copy array reflects the changes I make in the original array, rather than staying the same and letting me copy each cell.
Here's examples, assuming the array I'm trying to rotate is a piece of Tetris.
This does not work:
public abstract class Piece {
private int y;
private int x;
private String[][] tetromino;
public void setTetromino(String[][] a) { tetromino = a; }
public void rotate()
{
String[][] copy = tetromino;
tetramino[0][0] = copy[0][2];
tetramino[0][1] = copy[1][2];
tetramino[0][2] = copy[2][2];
tetramino[1][0] = copy[0][1];
tetramino[1][2] = copy[2][1];
tetramino[2][0] = copy[0][0];
tetramino[2][1] = copy[1][0];
tetramino[2][2] = copy[2][0];
}
public void print()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(tetromino[i][j]);
}
System.out.println();
}
}
}
And its subclass:
public class TPiece extends Piece {
String[][] a = {{ "1", "2", "3" },
{ "4", "5", "6" },
{ "7", "8", "9" }};
public TPiece()
{
setTetromino(a);
}
public static void main(String[] args)
{
TPiece T = new TPiece();
T.print();
T.rotate();
T.print();
}
}
Output:
123
456
789
369
658
363
Not rotated!
Now, for the working one, here's the changes to rotate() (everything else stays the same):
public void rotate() {
String[][] copy = new String[3][3];
copy[0][0] = tetromino[0][2];
copy[0][1] = tetromino[1][2];
copy[0][2] = tetromino[2][2];
copy[1][0] = tetromino[0][1];
copy[1][1] = tetromino[1][1];
copy[1][2] = tetromino[2][1];
copy[2][0] = tetromino[0][0];
copy[2][1] = tetromino[1][0];
copy[2][2] = tetromino[2][0];
tetromino = copy;
}
Output:
123
456
789
369
258
147
Rotated as intended.
Can anyone explain why?