Recursive patterns – the Koch curve (iii)

There is of course a cleaner way of generating a Koch curve in a recursive manner. It involves rethinking how the curve is generated. This method of generating the Koch curve takes a input the length of the line, and how many levels to generate. In the example below the length of the line is 243 pixels, and the depth is 3. In the base case a line is drawn of a required length, otherwise in the non-base case kochCurve() calls itself four times, each time with a length one-third of the length of the previous level. In between the the four calls, the position is rotated to create the ∧ shape.

Koch curve via quick recursion

The rotations needed to create the Koch curve.

Here is what the main function kochCurve()  looks like:

void kochCurve(float lngth, int level) {
  float newlngth;
  if (level == 0){
    forward(lngth);
    return;
  }
  else {
    newlngth = lngth/3.0;
    kochCurve(newlngth,level-1);
    rotation(-60);
    kochCurve(newlngth,level-1);
    rotation(120);
    kochCurve(newlngth,level-1);
    rotation(-60);
    kochCurve(newlngth,level-1); 
  }
}

Here are the ancillary functions:

void forward(float amount) {
  float newX = cx + cos(radians(angle)) * amount;
  float newY = cy + sin(radians(angle)) * amount;

  line(cx, cy, newX, newY);
  fill(0); 
  cx = newX;
  cy = newY;
}

void rotation(float degrees) {
  angle = angle + degrees;
}

And the Processing environment specs:

float angle = 0;
float cx;
float cy;

void setup() {
  size(400, 400);
  cx = 50;
  cy = height/2;
}

void draw() {
  background(255);
  stroke(0);
  kochCurve(243,4);
  noLoop();
}

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.