Need clarification on how this piece of found code is working (recursion)

rewritten in processing (and simplified)

void setup() {
  size(600, 600);
  background(100);
  textAlign(CENTER, CENTER);
  noLoop();
}

void draw() {
  background(100);
  fourRectangles(0, 0, width, 0);
}

//----------------------------------------------------------------------

void fourRectangles(float x, float y, 
  float sizeRect, 
  int depth) {
  // When the depth is still smaller than our random border 
  if (depth < random(0, 8)) {
    // split the rect in four parts and call me again (recursion)
    sizeRect     = sizeRect/2; // the new rects have half the size
    int newLevel = depth+1;    // the new rects have a depth that's higher than the old by 1 
    // 4 parts / quadrants 
    fourRectangles(x, y, sizeRect, newLevel);// upper left rect (comment one line out to see the missing quadrant)
    fourRectangles(x + sizeRect, y, sizeRect, newLevel); // upper right rect 
    fourRectangles(x + sizeRect, y + sizeRect, sizeRect, newLevel); // lower right rect 
    fourRectangles(x, y + sizeRect, sizeRect, newLevel); // lower left rect
  } else {
    // else: End of recursion: draw ONE rect (using the current local values)
    fill(random(255), random(255), random(255));
    rect(x, y, sizeRect, sizeRect);
    if (depth<=5) {
      fill(0);
      text(depth, x+sizeRect/2, y+sizeRect/2);
    }//if
  }//else
}//func

//-----------------------------------------------------------------------------------------------
// Inputs

void keyPressed() {
  redraw();
}

void mousePressed() {
  redraw();
}
//

1 Like