Monday, 10 April 2017

Map Generator in Unity C# _ 2

When to use recursive. 

I have been working on the map generation project / tutorial for a while. My way of doing the tutorial is briefly understand how to solve a problem and then try to figure out the functions / class / structure myself and then go back to read the tutorial code to see if there are any differences.

As I was working on identifying connected area in the map, I broke down my question to several layers:

Function1 : A function that return a list of connected area list.
void getAreaList(int[,] myMap, List<List<CoordTitle>> targetList )
the function iterates map[,], get the unchecked tiles, get the area list that connected to the given tile(Function2)

Function2:  get the area list that connected to the given tile
void getAreaTile(CoordTitle myRefTile, List<CoordTitle> resultTileList)

I started to think about recursive function here, as the algorithm is quite straight forward.  The function search the four neighbor tiles around it, and add the target tiles in the list, then iterate each result tile in the list, call the same function (recursive).

My first try is the recursive function :


It does the job. However I notice that in the tutorial, the author used a queue to store all the target tiles and do the checking process to all that in the queue. 

Here's the new function I made using the tutorial's algorithm.



So I asked myself, why not using recursive but queue in this situation. I did some research on other situations when recursive is the only solution : Tower of Hanoi, Fibonacci Sequence.

One key different element in connecting tiles problem is that : 
the calculation result of tile(n) does not rely on the result of tile(n-1). Instead of recursive, the connecting tiles function does the same thing to a collection, while the elements of collection is changing over time. The key problem to solve is pushing and popping correct elements from the collection.

The source code can be found here

both two functions can be found in the code.

Also, please forgive my Chinese comment, most of the Chinese comment are pseudocode written for myself before implementing the real functions.

No comments:

Post a Comment