140 likes | 272 Vues
This guide delves into advanced recursion techniques in Java, showcasing practical examples such as calculating factorials and drawing fractals. We'll start with the concept of factorials where the function recursively calls itself to compute n! (n factorial) using the equation factorial(n) = n * factorial(n - 1) for n > 1. Additionally, learn to create Sierpinski’s Gasket, a classic fractal, by recursive drawing of triangles within an equilateral triangle. Discover the approach to coding these examples in Java, illustrating the beauty of recursion in programming.
E N D
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
// created Sierpinski's gasket fractal public void sierpinski(int level) {// precondition: there is a blank picture at least // 291 x 281int p1X = 10;int p1Y = 280;int p2X = 290;int p2Y = 280;int p3X = 150;int p3Y = 110;Graphics g = this.getGraphics();g.setColor(Color.RED); drawGasket(g,level,p1X,p1Y,p2X,p2Y,p3X,p3Y); }
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 drawGasket(Graphics g, int level, int x1, int y1, int x2, int y2, int x3, int y3){ g.drawLine ( x1, y1, x2, y2); g.drawLine ( x2, y2, x3, y3); g.drawLine ( x3, y3, x1, y1); if ( level > 0 ) { int midx1x2 = (x1 + x2) / 2; int midy1y2 = (y1 + y2) / 2; int midx2x3 = (x2 + x3) / 2; int midy2y3 = (y2 + y3) / 2; int midx3x1 = (x3 + x1) / 2; int midy3y1 = (y3 + y1) / 2; drawGasket ( g, level - 1, x1, y1, midx1x2, midy1y2, midx3x1, midy3y1); drawGasket ( g, level - 1, x2, y2, midx2x3, midy2y3, midx1x2, midy1y2); drawGasket ( g, level - 1, x3, y3, midx3x1, midy3y1, midx2x3, midy2y3); }} Note how we decrease the level on the recursive calls Note2: We could also use Points instead of x’s and y’s
Assignment • No reading assignment from Media Computation