Recursive patterns – the Sierpinski Carpet

The Sierpinski Carpet is a fractal pattern first described by Waclaw Sierpinski in 1916. The Sierpinski carpet is self-similar pattern with 8 non-overlapping copies of itself. It starts with a solid white (255) square (in this case a 513×513). This is divided into nine smaller squares. The interior square is filled with black (0). This is the carpet at depth=1. Now subdivide each of the eight remaining squares into 9 squares and fill the centre square of each to obtain a carpet at depth=2. Continue doing this until a depth is reached. Below is an example.

Sierpinski Carpets of different depths: 1 to 4 (top 1,2; bottom 3,4)

What does the Processing code look like? The algorithm makes use of the Processing function rect() to mark a rectangle, and fill(0) to fill the rectangle with black (naturally any course could be specified).

int dim;
int limit, depth;

void setup() {
   size(513, 513);
   dim = 513;
   limit = dim;
   depth = 3;
}

void draw() {
   background(255);
   stroke(0);
   for (int i=1; i<=depth; i=i+1) {
      sierpinskiCarpet(0,0,dim);
      limit = limit / 3;
   }
   noLoop();
}

void sierpinskiCarpet(int x, int y, int size){
   if (size < limit)
      return;
   size = size / 3;
   for (int i=0; i<9; i=i+1)
      if (i == 4){
         fill(0);
         rect(x+size, y+size, size, size);
         noFill();
      }
      else
         sierpinskiCarpet(x+(i%3)*size, y+(i/3)*size, size);
}