0

I'm working with a 2D array and what I'm trying to do in the below method is swap two values. The 'currentBoard' variable is a 2D array that needs should not be edited. The 'cpy' variable a duplicate of the 'currentBoard' and needs its variables to be changed. 'nbt' and 'bt' are 1D arrays that used to point to an index in the 2D array. The code for the function 'copyBoard' is always below if it helps

The issue I'm having is that at on the line marked with ** when the value in the 'cpy' array is changed for some reason the value in 'currentBoard' is being changed as well. I really can't figure out why this is happening....


private void Swap(int[] nbt, int[] bt, ArrayList<State> children, String direction) {

    int[][] cpy = copyBoard(currentBoard);
    int temp = cpy[nbt[0]][nbt[1]];
    **cpy[nbt[0]][nbt[1]] = currentBoard[bt[0]][bt[1]];
    cpy[bt[0]][bt[1]] = temp;
    children.add(new Board(cpy, this.getGOAL(), this.getRows(), this.getColumns(), (this.getDirections() + direction + ", ")));
}

In case it helps here is the values that are assigned to the variables at the point when the code is on the line marked with **


nbt = {1, 0} bt = {0, 0}

private int[][] copyBoard(int[][] state)
{
    int[][] returnArray = new int[rows][columns];
    for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
    {
        returnArray[i] = state[i];
    }
    return returnArray;
}

1 Answer 1

6

A 2D array is an array of references to arrays. So if you assign returnArray[i] = state[i], you are simply making returnArray[i] refer to the same array that state[i] refers to. Thus, modifying returnArray[i][j] will modify the j'th element of whatever state[i] was. You have to create a deep copy of the "rows", too, e.g.:

private int[][] copyBoard(int[][] state)
{
    int[][] returnArray = new int[rows][columns];
    for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
    {
        // deep copy of row:
        returnArray[i] = Arrays.copyOf(state[i], state[i].length);
    }
    return returnArray;
}

Check out this short write-up on 2D arrays, it should give you a better idea of what's going on here. In particular, this little image, which represents int nums[][] = new int[5][4] (although it makes more sense in context):

enter image description here


By the way, your loop logic looks a little odd to me; even if the math happens to work out in your situation, it is a bit clearer to do this instead:

for (int i = 0; i < rows; i++)

Or more generally:

for (int i = 0; i < returnArray.length; i++)

These, of course, assume that state.length == rows; but you get the idea.

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

Comments

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.