开发者

Java: Randomizing the Order of Method Recursive Calls

开发者 https://www.devze.com 2023-03-01 15:50 出处:网络
For DFS maze generation in Java I wanna randomize the order in which the recursive calls of a DFS are made:

For DFS maze generation in Java I wanna randomize the order in which the recursive calls of a DFS are made:

for (int rows=i; rows<M; rows++)
    for (int cols=j; cols<N; cols++){

            if(northValid)
            {
                DFS(iNorth,j);
            }

            if(southValid){
                DFS(iSouth,j);
            }

            if(eastValid){
               开发者_开发问答 DFS(i, jEast);
            }

            if(westValid){
                DFS(i,jWest);
            }

How can I do that?


Switch on a call to the Random class:

Random r = new Random();
for (int rows=i; rows<M; rows++)
    for (int cols=j; cols<N; cols++) {
        bool found = false;
        while (!found)
            switch (r.next() % 4) {
                case 0: if(northValid) { DFS(iNorth,j); found = true; } break;
                case 1: if(southValid) { DFS(iSouth,j); found = true; } break;
                case 2: if(eastValid)  { DFS(i, jEast); found = true; } break;
                case 3: if(westValid)  { DFS(i, jWest); found = true; } break;
            }
    }

Note that, using this approach, you need to loop over the switch until it hits an available wall, and then continue. It's a bit inefficient, but quite simple.


Pseudo Code:

for (int rows=i; rows<M; rows++)
{
    for (int cols=j; cols<N; cols++)
    {
        // Generate a random number between 0 to 3 => %4
        switch(randomNumber)
        {
            case 0:  DFS(iNorth,j);
                     break;
            // ...

            case 3:  DFS(i,jWest);
                     break; 

            default: break;
        }
    }
}


I ended up using this:

 Double lottery = Math.random();

       for (int rows=i; rows<M; rows++)
           for (int cols=j; cols<N; cols++){


        if (lottery>=0.5D){
            if(northValid)
            {
                DFS(iNorth,j);
            }

            if(southValid){
                DFS(iSouth,j);
            }

            if(eastValid){
                DFS(i, jEast);
            }

            if(westValid){
                DFS(i,jWest);
            }


        }

       else if (lottery<0.5D)  
       {

            if(westValid){
                DFS(i,jWest);
            }

             if(eastValid){
                DFS(i, jEast);
            }

             if(southValid){
                DFS(iSouth,j);
            }

            if(northValid)
            {
                DFS(iNorth,j);
            }


       }

Worked well, thanks for the answers.

0

精彩评论

暂无评论...
验证码 换一张
取 消