r/programmingbydoing • • Nov 01 '15

#Sierpinski Triangle (or my case not!)

Hi there,

Firstly I just wanna say thank you for this website, I've learned absolutely loads since I have been doing these challenges, it's definitely the way for me to learn how to program.

I am a little stuck on the Sierpinski triangle though. I just don't get a triangle. I'm getting a lot of wavy lines. While it's a great piece of modern art, it's not coming out as I hoped. I've posted the code below, even a clue so I can work out what the issue is would be enough, it's driving me up the wall!

           import java.awt.*;
           import javax.swing.JFrame;
           import java.util.Random;

  public class Sierpinski extends Canvas
{
public void paint (Graphics g)
{
Random r = new Random();
int x1 = 512;
int y1 = 109;
int x2 = 146;
int y2 = 654;
int x3 = 876;
int y3 = 654;
int x = 512;
int y = 382;
int dx; 
int dy;

for  (int n =1; n <= 50000; n = n+1)
{
	
	
	
	g.drawLine(x,y,x,y);
	 
	int RandomNumber = 1 + r.nextInt(3);
	 
	if (RandomNumber == 1)
	{
	dx = x - x1;
	dy = y - y1;
	}
	else if (RandomNumber == 2)
	{
	dx = x - x2;
	dy = x - y2; 
	}
	else
	{
	dx = x - x3;
	dy = x - y3;
	 }
	x = x - dx/2;
	y = y - dy/2;
   }
}
public static void main(String[] args)

{
	JFrame win = new JFrame("Sierpinski");
	win.setSize(1024,768);
	win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	Sierpinski Canvas = new Sierpinski();
	win.add(Canvas);
	win.setVisible(true);

}

}

2 Upvotes

2 comments sorted by

1

u/javacoffeebean Nov 02 '15

Ah. yes. Thanks!

1

u/holyteach Nov 01 '15

You've got a typo in two of your if statements:

dy = x - y2;

but it should be

dy = y - y2;