moving_ninja
YaBB Newbies
Offline
Posts: 2
Recursively generating trees using linkedlists
May 9th , 2005, 7:49am
Just wondering if anyone else out there has encountered a similar problem to this and had any light to shed on it: In trying to write a program that creates a simple random tree using LinkedLists of Branch objects. That is, each branch has a list of branchs which stem from it and each of those has its own list of branches and so on. The only problem is that when I try to 'grow' the tree, the function which populates the list is recursive and goes off in one direction only creating branches on just one of the objects in the list. I understand this isnt the best explaination so here is the code: Branch root; int num_of_branches, tree_size; void setup() { size(500,500); background(0); stroke(255); strokeWeight(1); translate(250,450); tree_size = 0; num_of_branches = 10; root = new Branch(0,0,0,-60); } class Branch { int s_x, s_y, e_x, e_y; //start and end point coordinates LinkedList branches; Branch(int start_x, int start_y, int end_x, int end_y) { branches = new LinkedList(); //create end points based on start point this.s_x = start_x; this.s_y = start_y; this.e_x = end_x; this.e_y = end_y; this._draw(); this.grow(); } Branch(int start_x, int start_y) { branches = new LinkedList(); //create end points based on start point this.s_x = start_x; this.s_y = start_y; this.e_x = s_x - int(random(-50, 50)); this.e_y = s_y - int(random(50)); this._draw(); } void grow() { tree_size++; int num = int(random(num_of_branches)); println(num); //create branches for(int i=0;i<num;i++) { branches.add(new Branch(this.e_x, this.e_y)); } //for each branch in list, grow until some tree size is reached int s = branches.size(); for(int i=0;i<s;i++) { Branch temp = (Branch) branches.get(i); if(tree_size<20) { temp.grow(); } } } void _draw() { line(this.s_x, this.s_y, this.e_x, this.e_y); } } If anyone else out there has had a go with anything similar to this, id be really interested to know what would be a good angle to go about populating all the branches in one recursive function to create a more realistic tree. cheers for your time anyway, paul.