
// SierpinskiTriangles.java
// Robert Sedgewick and Kevin Wayne
// Slightly reformatted by Andrew Davison, Nov. 2022

/* Draw the Sierpinski gasket.

   Usage:
     > compile SierpinskiTriangles.java
     > run SierpinskiTriangles n
   e.g.
     > run SierpinskiTriangles 6
*/


public class SierpinskiTriangles
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run SierpinskiTriangles <level>");
      return;
    }

    int n = Integer.parseInt(args[0]);     // number of discs
    double[] x = { 0.0, 0.5, 1.0}; // coordinates of main triangle
    double[] y = { 0.0, (Math.sqrt(3.0)/2.0), 0.0};
    StdDraw.polygon(x, y);
    draw(n, x[0], y[0], x[1], y[1]);
    System.out.println("Drawing finished");
  }  // end of main()


  private static void draw(int n, double x0, double y0, 
                                  double x1, double y1)
  {
    if (n == 0)
      return;

    // calculate coordinates
    double x[] = { x0+(x1-x0)/2.0, x1, (x1+(x1-x0)/2.0)};
    double y[] = { y0+(y1-y0)/2.0, y0, y0+(y1-y0)/2.0};

    // draw 1 triangle at current position
    StdDraw.polygon(x, y);

    // call function at each of the 3 corners
    draw(n-1, x0, y0, x[0], y[0]);
    draw(n-1, x[0], y[0], x1, y1);
    draw(n-1, x[1], y[1], x[2], y[2]);
  }  // end of draw()

}  // end of SierpinskiTriangles class
