More About Recursion 2 Java Looking at more
More About Recursion - 2 Java
Looking at more recursion in Java A simple math example Fractals
A simple math example Calculating n! factorial (n) = n * factorial (n-1) if n>1 factorial (1) = 1 How do we code this in Java?
Fractals Sierpinski’s Gasket Starting with an equilateral triangle, recursively drawing smaller equilateral triangles inside, by building triangles of the midpoints
SG(0)
SG(1)
SG(2)
SG(3)
SG(4)
SG(5)
// created Sierpinski's gasket fractal public void sierpinski(int level) { // precondition: there is a blank picture at least // 291 x 281 int p 1 X = 10; int p 1 Y = 280; int p 2 X = 290; int p 2 Y = 280; int p 3 X = 150; int p 3 Y = 110; Graphics g = this. get. Graphics(); g. set. Color(Color. RED); draw. Gasket(g, level, p 1 X, p 1 Y, p 2 X, p 2 Y, p 3 X, p 3 Y); }
How do we solve the problem? Well, draw the line segments for the triangle Then, if the level is at least 1, calculate the midpoints, and make the 3 recursive calls on the sub-triangles
private void draw. Gasket(Graphics g, int level, int x 1, int y 1, int x 2, int y 2, int x 3, int y 3) { g. draw. Line ( x 1, y 1, x 2, y 2); g. draw. Line ( x 2, y 2, x 3, y 3); g. draw. Line ( x 3, y 3, x 1, y 1); if ( level > 0 ) { int midx 1 x 2 = (x 1 + x 2) / 2; int midy 1 y 2 = (y 1 + y 2) / 2; int midx 2 x 3 = (x 2 + x 3) / 2; midy 2 y 3 = (y 2 + y 3) / 2; int midx 3 x 1 = (x 3 + x 1) / 2; int midy 3 y 1 = (y 3 + y 1) / 2; } } draw. Gasket ( g, level - 1, x 1, y 1, midx 1 x 2, midy 1 y 2, midx 3 x 1, midy 3 y 1); draw. Gasket ( g, level - 1, x 2, y 2, midx 2 x 3, midy 2 y 3, midx 1 x 2, midy 1 y 2); draw. Gasket ( g, level - 1, x 3, y 3, midx 3 x 1, midy 3 y 1, midx 2 x 3, midy 2 y 3); Note how we decrease the level on the recursive calls Note 2: We could also use Points instead of x’s and y’s
Assignment No reading assignment from Media Computation
- Slides: 14