Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Sierpinski triangle

807607Nov 22 2006 — edited Nov 22 2006
So, I'm trying to code a method that draws a sierpinski triangle. I'm about 90% there but for some reason, the bottom right triangle does not draw. I cannot, for the life of me figure it out.

Thanks for any help that you can provide.

Here's the class:
import java.awt.*;
import java.lang.Math.*;

public class SerpinskiDraw implements ParentDraw
{ 
  	private Graphics g_parent;
  	
  	int num_points = 3;
  
  	public void Draw(Graphics g, int w, int h, int level) {
  	
  		g_parent = g;
    
		//set up coordinate arrays for the x and y points of the triangle.
		//w and h are the width and height of the drawing canvas as hard set in Canvas0
	
		int[] x = new int [3];
		x[0] = (int) (.1 * (double) w);
		x[1] = (int) (.5 * (double) w);
		x[2] = (int) (.9 * (double) w);
	
	
		int[] y = new int [4];
		y[0] = (int) (.9 * (double) h);
		y[1] = (int) (.1 * (double) h);
		y[2] = (int) (.9 * (double) h);

		//draw the triangle just specified.  We draw this triangle in white so that when the black
		//triangles are drawn by the Serpinski recursive method, we do not
		//have to separately color the center triangle white.
		
		g_parent.setColor(Color.white);
		g_parent.fillPolygon(x, y, num_points);

		
		Serpinski(0, level, x, y, num_points);  //now Serpinski this triangle
  	
  	}
  
  	/**
  	 * You will need to define this function recursively. 
  	 */

  	public void Serpinski (int depth, int level, int x[], int y[], int num_points) {
  		
  		// base case
		if(depth == level) {
  			g_parent.fillPolygon(x, y, num_points);
  			g_parent.setColor(Color.black);
  		}
		
		// recursive
  		else {
  			depth++;
  			  			
  			// Calculates the x-coords
  			int x0 = (x[0] + x[1])/2;
  			int x1 = (x[0] + x[2])/2;
  			int x2 = (x[1] + x[2])/2;
  			
  			// Calculates the y-coords
  			int y0 = (y[0] + y[1])/2;
  			int y1 = (y[0] + y[2])/2;
  			int y2 = (y[1] + y[2])/2;

			// Creates arrays to pass to the graphics object
  			// Top
  			int[] xCoord0 = {x[0], x0, x1};
  			int[] yCoord0 = {y[0], y0, y1};
			Serpinski(depth, level, xCoord0, yCoord0, num_points);
  			
  			// Should be bottom left, does not draw
  			int[] xCoord1 = {x0, x[1], x2};
  			int[] yCoord1 = {y0, y[1], y2};
			Serpinski(depth, level, xCoord1, yCoord1, num_points);
  			
  			// Bottom Right
  			int[] xCoord2 = {x1, x2, x[2]};
  			int[] yCoord2 = {y1, y2, y[2]};
			Serpinski(depth, level, xCoord2, yCoord2, num_points);
  		}
  	
   	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 20 2006
Added on Nov 22 2006
7 comments
375 views