문제

Hey people i have this structure for the search tree

class State
{
    //CLASS STATE
    int value;
    char[][] state; //the game Grid 
    State child[]; // children of current state, maximum is 8
    State(char[][] src)
    {
        state=src;
        child=new State[8];
    }

this is the root node definition

 State rootNode = new State(currentGrid);
 rootNode.value=-1;
 int v =maxValue(rootNode,depth);

after the end of recursion in the max value function the array in rootNode should not be edited since its the the first state but when i Display it i get an array filled with stuff which means that the rootNode.state passed by reference to the max value function :(

//i am trying to implement MiniMax Algorithm.

도움이 되었습니까?

해결책

If you don't want objects that are passed as parameters to be changed, pass in a copy (or make a copy of the parameter inside the method).

Note that char[][] means you have an array of char arrays, i.e. you are working with objects and if you copy the first level you still might have a reference to the second.

Thus you might have to loop through the first level/dimension and copy all the arrays in there, like this:

char target[][] = new char[state.length][0];

for( int i = 0; i < state.length; ++i ) { 
  target[i] = Arrays.copyOf(state[i], state[i].length);
}

다른 팁

If you need, you can easily create a copy of the array through Arrays.copyOf

You can also create a deep copy. How to do this has been answered here: How to deep copy an irregular 2D array

Yes, Java passes references to arrays and not the array as a value. So if you give a reference to your internal state away, the receiver can change it and the change is "visible" in the source (in fact: it's only one array that has been changed and all reference holders will see the change).

Quick fix/solution: clone your state array and pass a reference to this clone instead of the original. This will keep your internal root state unmodified.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top