[英]recursive Sierpinski triangle not recursive
我正在為遞歸的Sierpinski三角形編寫程序,但不知道如何更改數組xm[]
和ym[]
中的點以實現此目的。 更具體地說,當我運行該程序時,只繪制了一個帶有一個藍色內部三角形的輪廓三角形。 任何幫助將不勝感激!
public class recursiveSierpinski {
public static void draw(int n, double x0, double y0, double x1,
double y1, double x2, double y2) {
// if reach base case, method return
if (n==0) return;
// define array xm, ym to store x and y values of midpoints
double [] xm = new double[3];
double [] ym = new double[3];
// assign midpoints’ values to xm and ym
xm[0]= (x0+x1)/2;
xm[1]= (x1+x2)/2;
xm[2]= (x2+x0)/2;
ym[0]= (y0+y1)/2;
ym[1]= (y1+y2)/2;
ym[2]= (y2+y0)/2;
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledPolygon(xm, ym); //this makes triangle
xm[0]=xm[0]/2.0;
ym[0]=ym[0]/2.0;
xm[1]=xm[1]/2.0;
ym[1]=ym[1]/2.0;
xm[2]=xm[2]/2.0;
ym[2]=ym[2]/2.0;
draw(n,xm[0],ym[0],xm[1],ym[1],xm[2],ym[2]);
draw(n,xm[1],ym[1],xm[2],ym[2],xm[0],ym[0]);
draw(n,xm[2],ym[2],xm[0],ym[0],xm[1],ym[1]);
// recursively draw the sub triangles (?)
}
public static void main(String[] args) {
// N levels of recursion
int N = Integer.parseInt(args[0]);
// outline the triangle
double t = Math.sqrt(3.0) / 2.0;
StdDraw.line(0.0, 0.0, 1.0, 0.0);
StdDraw.line(1.0, 0.0, 0.5, t);
StdDraw.line(0.5, t, 0.0, 0.0);
draw(N, 0.0, 0.0, 0.5, t, 1.0, 0.0);
}
}
嘗試這個:
public class recursiveSierpinski {
public static void draw(int n, double x0, double y0, double x1,
double y1, double x2, double y2) {
// if reach base case, method return
if (n==0) return;
// define array xm, ym to store x and y values of midpoints
double [] xm = new double[3];
double [] ym = new double[3];
// assign midpoints’ values to xm and ym
xm[0]= (x0+x1)/2;
xm[1]= (x1+x2)/2;
xm[2]= (x2+x0)/2;
ym[0]= (y0+y1)/2;
ym[1]= (y1+y2)/2;
ym[2]= (y2+y0)/2;
StdDraw.filledPolygon(xm, ym); //this makes triangle
draw(n-1,xm[0],ym[0],xm[1],ym[1],x1,y1);
draw(n-1,xm[1],ym[1],xm[2],ym[2],x2,y2);
draw(n-1,xm[2],ym[2],xm[0],ym[0],x0,y0);
}
public static void main(String[] args) {
// N levels of recursion
int N = Integer.parseInt(args[0]);
// outline the triangle
double t = Math.sqrt(3.0) / 2.0;
StdDraw.setPenColor(StdDraw.BLACK);
// fill arrays initially to draw black solid TRIANGLE xm, ym = 0.0, 0.0, 0.5, t, 1.0, 0.0
StdDraw.filledPolygon(xm, ym);
StdDraw.setPenColor(StdDraw.WHITE);
draw(N, 0.0, 0.0, 0.5, t, 1.0, 0.0);
}
}
關於托馬斯的好答案
實際上應該是
draw(n-1,x0,y0,xm[0],ym[0],xm[2],ym[2]); draw(n-1,xm[0],ym[0],x1,y1,xm[1],ym[1]);
draw(n-1,xm[1],ym[1],xm[2],ym[2],x2,y2);
因此,根據我的說法,最后一行應該有所不同。
您不必再更改它們。 假設您的參數代表三角形的點,則在您執行fillPolygon調用之后,您已經計算出了點。
對於三角形ABC,您已經找到中點AB,BC,AC。
因此,您可以遞歸在三角形A-AB-AC,三角形AB-B-BC和三角形BC-C-AC上調用Sierpinski。
就您的代碼而言,您將在fillPolygon()調用之后刪除對xm和ym的更改,並照此調用draw。 還要注意,您想要n-1,否則將無限遞歸。
draw(n-1,x0,y0,xm[0],ym[0],xm[2],ym[2]);
draw(n-1,xm[0],ym[0],x1,y1,xm[1],ym[1]);
draw(n-1,xm[1],ym[1],x2,y2,xm[0],ym[0]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.