I followed the Shiffmans tutorial about recursion to end up with this:
As you can see its not perfect and I think the code can be optimized. How do I get rid of the thick lines that should´t be there? And if you get an idea of how I could optimize this code tell me please!
This was made with processing 3.3.6 and the code is the following:
void setup() {
size(800, 800);
}
void draw() {
background(255);
fill(0);
noStroke();
rectMode(CENTER);
Serpinski(width/2, height/2, width/3);
}
void Serpinski(int x, int y, int d) {
rect(x, y, d, d);
if (d > 1) {
Serpinski(int(x+ d), y, d*1/3);
Serpinski(int(x- d), y, d*1/3);
Serpinski(x, int(y+ d), d*1/3);
Serpinski(x, int(y- d), d*1/3);
Serpinski(int(x+ d), int(y+ d), d*1/3);
Serpinski(int(x- d), int(y- d), d*1/3);
Serpinski(int(x+ d), int(y- d), d*1/3);
Serpinski(int(x- d), int(y+ d), d*1/3);
}
}
As mentioned in the comments, changing the Sierpinski method so it deals with float values instead of int will help.
void setup() {
size(800, 800);
}
void draw() {
background(255);
fill(0);
noStroke();
rectMode(CENTER);
Serpinski(width/2, height/2, width/3);
}
void Serpinski(float x, float y, float d) {
rect(x, y, d, d);
if (d > 1) {
Serpinski( x+ d, y, d/3);
Serpinski( x- d, y, d/3);
Serpinski( x, y+ d, d/3);
Serpinski( x, y- d, d/3);
Serpinski( x+ d, y+ d, d/3);
Serpinski( x- d, y- d, d/3);
Serpinski( x+ d, y- d, d/3);
Serpinski( x- d, y+ d, d/3);
}
}
However, due to the way the pixel information is handled, you will find that the graphic representation is still not "exact" when you get down to the smaller rectangles. One way to achieve that is to change the size of the sketch to one that is a power of 3:
size(729, 729);
As for optimization, you could call the Sierpinski method in setup(), that way it only gets computed once rather than every time draw() is called.