Download presentation

Presentation is loading. Please wait.

Published byMorgan Owenby Modified over 2 years ago

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 281 int 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

Similar presentations

OK

Picture It Very Basic Game Picture Pepper. Original Game import java.util.Scanner; public class Game { public static void main() { Scanner scan=new Scanner(System.in);

Picture It Very Basic Game Picture Pepper. Original Game import java.util.Scanner; public class Game { public static void main() { Scanner scan=new Scanner(System.in);

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on ideal gas law Ppt on p&g products philippines Ppt on game theory john Ppt on coalition government australia Ppt on places in our neighbourhood living Ppt on history and sport the story of cricket Ppt on water pollution in delhi Ppt on network switching subsystem Mp ppt online form 2016 Ppt on paintings and photographs related to colonial period clothing