Last active
April 20, 2024 22:39
-
-
Save evinjaff/d1450a8361de4e27703c108b11ac6fd2 to your computer and use it in GitHub Desktop.
Recursive Sierpinski Triangle in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Color; | |
import sedgewick.StdDraw; | |
public class Triangles { | |
public static void triangle(double x, double y, double s, int n){ | |
// X and y are base coordinates, s is size, n is number of recursions | |
if(n<=0) { | |
return; | |
} | |
StdDraw.setPenColor(Color.black); | |
StdDraw.setPenRadius(.0005); | |
//triangle coordinates | |
double x1 = x; | |
double y1 = y; | |
double x2 = x1 + s; | |
double y2 = y1; | |
double x3 = (x1+x2)/2.0; | |
double y3 = y1 + (Math.sqrt(3)*s/2); | |
StdDraw.line(x1, y1, x2, y2); | |
StdDraw.line(x1, y1, x3, y3); | |
StdDraw.line(x2, y2, x3, y3); | |
triangle(x1, y1, s/2.0, n-1); | |
triangle((x1 + x2)/2.0, (y1 + y2)/2.0, s/2.0, n-1); | |
triangle((x1 + x3)/2.0, (y1+y3)/2.0, s/2.0, n-1); | |
} | |
public static void main(String[] args) { | |
triangle(0, 0, 1, 5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment