I defined an ArrayList
of matrix (Integer[][]
) in Java. When I add a new matrix into the ArrayList
, it changes all of the variables to the last matrix.
I mean when I add
0 4 4 2
0 4 4 2
1 2 3 4
4 5 9 7
and then add
1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3
When I print the elements like that:
1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3
-------
1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3
So what should I do for this? this is my code :
private Integer matrix[][] = new Integer[4][4];
public Integer[][] right(Integer[][] M) {
for (int k = 0; k < 4; k++)
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
if (M[i][j] != 0 && M[i][j + 1] == 0) {
M[i][j + 1] += M[i][j];
M[i][j] = 0;
new_tile = true;
}
}
for (int i = 0; i < 4; i++)
for (int j = 3; j > 0; j--) {
if (M[i][j] == M[i][j - 1] && M[i][j] != 0 && M[i][j - 1] != 0) {
M[i][j] += M[i][j - 1];
M[i][j - 1] = 0;
new_tile = true;
}
}
for (int k = 0; k < 4; k++)
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
if (M[i][j] != 0 && M[i][j + 1] == 0) {
M[i][j + 1] += M[i][j];
M[i][j] = 0;
new_tile = true;
}
}
return M;
}
static void printMatrix(Integer[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
/**
* Print the elements in a matrix list
*/
static void printMatrices(ArrayList<Integer[][]> matrices) {
for (Integer[][] matrix : matrices) {
printMatrix(matrix);
System.out.println("--------");
}
}
public void solve() {
Integer[][] temp = right(matrix);
printMatrix(temp);
if (new_tile)
visited_nodes.add(temp);
else {
printMatrices(visited_nodes);
}
refresh();
}
@Override
public void actionPerformed(ActionEvent e) {
solve();
repaint();
}
and the solve method called every 100ms.