I've been trying to solve a problem that requires a couple of methods:
IT LOOKS LIKE A LOT, but you don't really need to read the methods. Just know that I'm passing an int[][]
to a method, changing the int[][]
inside the method, then checking for equality to an int[][]
outside the method.
public static boolean One(int[][] matrix){
matrix = transpose(matrix);
matrix = reverseRow(matrix);
return Arrays.deepEquals(matrix, changed);
}
public static boolean Two(int[][] matrix){
//180 degree clockwise
matrix = transpose(matrix);
matrix = reverseRow(matrix);
matrix = transpose(matrix);
matrix = reverseRow(matrix);
return Arrays.deepEquals(matrix,changed);
}
public static int[][] transpose(int[][] matrix){
for(int i = 0; i < N; i++) {
for(int j = i+1; j < N; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return matrix;
}
public static int[][] reverseRow(int[][] matrix){
for(int j = 0; j < N; j++){
for(int i = 0; i < N / 2; i++) {
int temp = matrix[j][i];
matrix[j][i] = matrix[j][N - i - 1];
matrix[j][N - i - 1] = temp;
}
}
return matrix;
}
public static int[][] reverseCol(int[][] matrix){
for(int col = 0;col < matrix[0].length; col++){
for(int row = 0; row < matrix.length/2; row++) {
int temp = matrix[row][col];
matrix[row][col] = matrix[matrix.length - row - 1][col];
matrix[matrix.length - row - 1][col] = temp;
}
}
return matrix;
}
The structure of the problem is as follows: I have an int[][] of original numbers I have an int[][] of numbers, that is a result of a transformation of the original numbers. Specifically, a 90 degree clockwise turn, and an 180 degree clockwise turn.
The actual problem is much bigger, but I think there's a rule against getting straight up answers to problems, so I cut it down to what I need.
The problem is this: After I run method one, the original array becomes modified, so it's corrupted before I run method two.
For instance, Original before method One:
1111
0000
0000
0000
Original after method One;
0001
0001
0001
0001
These changes happens right after I run transpose(matrix) and reverseRow(matrix). Note that in java debug mode, I can see original being changed when I step over these methods. I DIDN'T EVEN MENTION ORIGINAL. I modified a passed of a passed version of Original.
So, 3 questions:
I thought that objects passed to methods don't get changed unless you return the changed object and then set the original to the changed in main() or the original method? I'm not talking about transpose, or reverseRow, because those were supposed to change matrix inside method One.
I tested this out with a method using strings. My belief above held true. Are int[][]'s different?
How can I fix it so that original doesn't get changed? Or am I missing something really simple?