1 / 14

More About Recursion - 2

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

lane-levy
Download Presentation

More About Recursion - 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. More About Recursion - 2 Java

  2. Looking at more recursion in Java • A simple math example • Fractals

  3. 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?

  4. Fractals • Sierpinski’s Gasket • Starting with an equilateral triangle, recursively drawing smaller equilateral triangles inside, by building triangles of the midpoints

  5. SG(0)

  6. SG(1)

  7. SG(2)

  8. SG(3)

  9. SG(4)

  10. SG(5)

  11. // 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); }

  12. 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

  13. 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

  14. Assignment • No reading assignment from Media Computation

More Related