简体   繁体   中英

Javascript recursion for tree creation

i am trying to create funcion for creating decision tree with state of game in every node in game (doesnt matter what game). I wrote recursive function (DFS) like this:

function makeTree(anchor,count,player){
    var subTree=null;
    var nodes=[];
    if(player)var newPlayer=false;
    else var newPlayer=true;
    for (var i = 0; i <= 9; i++) {
        for (var j = 0; j <= 9; j++) {
            if(anchor["state"][i][j]==0){
                var newState=anchor["state"];
                if(player)newState[i][j]=1;
                else newState[i][j]=2;
                var node={name:i+"_"+j, contents:[],state:newState, value:null, player:newPlayer};
                if(count>0){
                    var newCount=count-1;
                    subTree=makeTree(node,newCount,newPlayer);
                    node["contents"]=subTree;
                }
                nodes.push(node);
            }else{
                continue;
            }
        }
    }
    return nodes;
}

And with call:

var tree={};
var hrac=true;
var plocha=[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0]];
var state=plocha;
    tree={name: "root",
          contents:[], 
          state:state, 
          value:null, 
          player: hrac};
    tree["contents"]=makeTree(tree,3,hrac);

But the function change variables in different scope, so the output tree will be like this:

"root" - node - node - node
                     - node
                     - node
                     - node
                     - node

I cant figure out what is going on with variable newState in that function, because after finish the recursion the original variable plocha has the value of the latest node["state"] . Any suggestions what to do?

EDIT: Thanks to Bergi i realize that i need to do deep copy of array insted of make reference to it, so i make funcion for copy of array and now this works. Thank you Bergi!

Your state property is an array, which is mutable. On every assignment, you change the one multidimensional array that is the state of all nodes. You'll want to make every newState a new array, instead of passing your plocha reference recursively through all functions:

 …
 var newState = anchor["state"].slice(); // create copy of the outer array
 newState[i] = newState[i].slice(); // copy of the row to be modified
 newState[i][j] = player ? 1 : 2;
 …

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM