Loading in 5 sec....

More About Recursion - 2 PowerPoint Presentation

More About Recursion - 2

- 62 Views
- Uploaded on
- Presentation posted in: General

More About Recursion - 2

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

More About Recursion - 2

Java

- A simple math example
- Fractals

- Calculating n!
- factorial (n) = n * factorial (n-1) if n>1
- factorial (1) = 1
- How do we code this in Java?

- 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);

}

- 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

- No reading assignment from Media Computation