Recursion Form

x = y = 10
graphics.lineStyle(1,0);
drawBox(6);

function drawBox(iter:Number=10, count:Number=1, y:Number=0, w:Number=500):void{
       if (count < iter){
               var width:Number = w / count
               for (var i:int = 0; i<count; i++){
                   graphics.drawRect(i * width, width * count/w, width, width);
               }
               count++;
               drawBox(iter, count, y, width);
       }
}

This small snippet just draws this image:

If you have an idea for a short recursive snippet. Feel free to post it in the comments.

6 comments

  1. nice snippet ! here is my version of the shortest recursive snippet ever for removing all display objects in a MovieClip:
    while(holder_mc.numChildren) {
    holder_mc.removeChild(holder_mc.getChildAt(0));
    }

  2. var x0:int = 275;
    var y0:int = 200;

    graphics.lineStyle(1, 0);
    graphics.moveTo(x0, y0);

    drawSpiral(300);

    function drawSpiral(max:int, r:Number = 0, a:Number = 0, c:int = 0):void {
    graphics.lineTo(Math.cos(a) * r + x0, Math.sin(a) * r + y0);
    r += 1;
    a += 0.1;

    if (++c < max) { drawSpiral(max, r, a, c); } }

  3. when you think recursion, who doesn’t think “Fibonacci”? So here’s a 2 fer 1:

    var totalIterations:int = 10;
    var baseWidth:Number = 5;
    var xp:Number = stage.stageWidth >> 1;
    var yp:Number = stage.stageHeight >> 1;

    plot(0, 0);

    function plot(i:int, c:int):void {
    var n:Number = fib(i);
    var r:Rectangle = getRect(this);
    var nr:Rectangle = new Rectangle();
    nr.width = nr.height = baseWidth * n;
    graphics.lineStyle(0, 0xFF0000);
    if (c == 0) {
    xp = r.x || xp;
    yp = yp – baseWidth * n;
    nr.x = xp;
    nr.y = yp;
    graphics.moveTo(nr.x + nr.width, nr.y);
    graphics.curveTo(nr.x, nr.y, nr.x, nr.y + nr.height);
    } else if (c == 1) {
    xp = xp + r.width;
    yp = r.y || yp;
    nr.x = xp;
    nr.y = yp;
    graphics.moveTo(nr.x, nr.y);
    graphics.curveTo(nr.x + nr.width, nr.y, nr.x + nr.width, nr.y + nr.height);
    } else if (c == 2) {
    yp = yp + r.height;
    xp = r.x;
    nr.x = xp;
    nr.y = yp;
    graphics.moveTo(nr.x + nr.width, nr.y);
    graphics.curveTo(nr.x + nr.width, nr.y + nr.height, nr.x, nr.y + nr.height);
    } else if (c == 3) {
    xp = xp – baseWidth * n;
    yp = r.y;
    nr.x = xp;
    nr.y = yp;
    graphics.moveTo(nr.x, nr.y);
    graphics.curveTo(nr.x, nr.y + nr.height, nr.x + nr.width, nr.y + nr.height);
    }

    graphics.lineStyle(0, 0x000000);
    graphics.drawRect(nr.x, nr.y, nr.width, nr.height);

    if (++c > 3) c = 0;

    if (++i < totalIterations) plot(i, c); } function fib(num:int):Number{ if (num <= 1) return num; else return fib(num-1)+fib(num-2); }

Leave a Reply

Your email address will not be published. Required fields are marked *