Tag Archives: recursion

Recursive Tree

Actionscript:
  1. var branches:int = 0;
  2. var maxBranches:int = 400;
  3.  
  4. graphics.lineStyle(0,0x000000);
  5.  
  6. makeBranch(300,350,100,-45,45);
  7.      
  8. function makeBranch(xp:Number, yp:Number, leng:Number, min:Number, max:Number):void {
  9.  
  10.     var endX:Number, endY:Number;
  11.     var theta:Number = (min + Math.random()*(max-min) - 90) * Math.PI / 180;
  12.      
  13.     endX = xp + leng * Math.cos(theta);
  14.     endY = yp + leng * Math.sin(theta);
  15.  
  16.     graphics.moveTo(xp, yp);
  17.     graphics.lineTo(endX, endY);
  18.    
  19.     if (branches <maxBranches) {
  20.         var newLength:Number = leng*.7;
  21.         setTimeout(makeBranch, 0, endX, endY, newLength, -90, 0);
  22.         setTimeout(makeBranch, 0, endX, endY, newLength, 0, 90);
  23.     }
  24.     branches+=2;
  25. }

Draws a tree using recursion.

Posted in Graphics, functions | Also tagged , , | Leave a comment

Recursion Trick w/ setTimeout()

Actionscript:
  1. var counter:int = 0;
  2.  
  3. graphics.lineStyle(0,0x000000);
  4.  
  5. recursive();
  6.  
  7. function recursive():void{
  8.    
  9.     if (counter <4000){
  10.        graphics.moveTo(10,10);
  11.        graphics.lineTo(counter, 200);
  12.        counter+=4;
  13.           // don't call recursive(), use setTimeout instead
  14.        setTimeout(recursive,0);
  15.     }else{
  16.         trace(counter / 4 + " lines were drawn");
  17.     }

Be careful with this one, if you don't know what your doing you may be able to crash flash.

Anyway... if you use a recursive function in flash you may find yourself getting a stack overflow error. You can avoid this by using setTimeout():

Actionscript:
  1. // don't call recursive(), use setTimeout() instead
  2. setTimeout(recursive,0);

Of course... the stack overflow error is there for a reason, if used incorrectly you could bring the flash player to a standstill.

You can also achieve animated recursion by actually adding a delay to your setTimout() call:

Actionscript:
  1. // don't call recursive(), use setTimeout() instead
  2. setTimeout(recursive,10);

Posted in functions | Also tagged , , | Leave a comment