Introduction
Source code for all exercises of session 4.
Exercises
Exercise 1: implement an IFS
void drawIFS(double x, double y, int depth) {
double nx;
double ny;
// halting condition
if (depth < 0) {
// put pixel after proper scaling
point((int)((1-x)*width), (int)((1-y)*height));
return;
}
// trans.length = n
for (int i=0; i < trans.length; i++) {
// x' = x*a + y*b + e
// y' = x*c + y*d + f
nx = x*trans[i][0] + y*trans[i][1] + trans[i][4];
ny = x*trans[i][2] + y*trans[i][3] + trans[i][5];
// recurse
drawIFS(nx, ny, depth-1);
}
}
Exercise 2: Sierpinsky
The parameters below result in a possible Sierpinsky triangle:
| a | b | c | d | e | f |
| 0.5 | 0 | 0 | 0.5 | 0 | 0 |
| 0.5 | 0 | 0 | 0.5 | 0.5 | 0 |
| 0.5 | 0 | 0 | 0.5 | 0 | 0.5 |
Another possible solution is:
| a | b | c | d | e | f |
| 0.5 | 0 | 0 | 0.5 | 0.25 | 0.5 |
| 0.5 | 0 | 0 | 0.5 | 0 | 0 |
| 0.5 | 0 | 0 | 0.5 | 0.5 | 0 |
Exercise 3: Koch's Snowflake
private static final double dr = 1/Math.sqrt(12);
public void drawSnowFlake(int d, Point p1, Point p5) {
if (d<=0)
line((int)p1.x, (int)p1.y, (int)p5.x, (int)p5.y);
else {
double dx = p5.x - p1.x;
double dy = p5.y - p1.y;
Point p2 = new Point(dx/3 + p1.x, dy/3 + p1.y);
Point p3 = new Point(p1.x + dx/2 + dy*dr, p1.y + dy/2 - dx*dr);
Point p4 = new Point(2*dx/3 + p1.x, 2*dy/3 + p1.y);
drawSnowFlake(d-1, p1, p2);
drawSnowFlake(d-1, p2, p3);
drawSnowFlake(d-1, p3, p4);
drawSnowFlake(d-1, p4, p5);
}
}