I want to check if a variable ("matrix") is changed when sent to a specific function ("moveAround"), so I created another variable ("matrixB") and I gave it the value that comes from the function given the first variable, and now I compare the two variables.
The problem is that for some reason the first variable is changed as well as the second.
The code looks like this:
matrixB = moveAround(matrix, userDir);
cmpMatrices(matrix, matrixB);
The function "moveAround" is meant to return a different matrix then given (most of the time). the function "cmpMatrices" returns true if the two matrices are alike, and false there is at least one component that does not equal.
For some reason when I get "matrixB" from the "moveAround" function after giving it "matrix" it changes both "matrix" and "matrixB".
The function "moveAround" calls another function name "moveUp"/"moveDown"/"moveRight"/"moveLeft" in respect to "userDir".
The function "moveUp" looks like this:
public static int[][] moveUp(int[][] matrix) {
int i, j, m;
for (j = 0; j < matrix.length; j++) {
m = 1;
for (i = 0; i + m < matrix.length;) {
if (matrix[i + m][j] == 0) {
m++;
} else {
if (matrix[i + m][j] == matrix[i][j]) {
matrix[i][j] = 2 * matrix[i][j];
matrix[i + m][j] = 0;
i++;
} else {
if (matrix[i][j] == 0) {
matrix[i][j] = matrix[i + m][j];
matrix[i + m][j] = 0;
m++;
} else {
if (m != 1) {
matrix[i + 1][j] = matrix[i + m][j];
matrix[i + m][j] = 0;
i++;
} else {
i++;
}
}
}
}
}
}
return matrix;
}
The other move Down/Right/Left are very similar just different direction.
The function "cmpMatrices" looks like this:
public static boolean cmpMatrices(int[][] matrixA, int[][] matrixB){
for(int i = 0; i < matrixA.length; i++){
for(int j = 0; j < matrixA[i].length; j++){
if(matrixA[i][j] != matrixB[i][j]){
return false;
}
}
}
return true;
}