2012-04-02 4 views
1

삼각형 수를 세기 위해이 Sierpinski의 삼각형 프로그램을 수정해야합니다. 그래서 삼각형을 만들 때마다 카운트를 증가 시키려고했지만, 어떻게 든 카운트가 증가하지 않습니다.Sierpinski 삼각형의 삼각형 수를 계산하십시오

public class SierpinskiTriangle extends Applet 
{ 

    public int SeirpTri(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int n, int count) 
    { 
     this.setBackground(new Color(0,0,0)); 
     this.setSize(700, 500); 
     if (n == 0) 
     { 
      g.setColor(new Color(0, 255, 0)); 
      g.drawLine(x1, y1, x2, y2);  // if n = 0 draw the triangle 
      g.drawLine(x2, y2, x3, y3); 
      g.drawLine(x3, y3, x1, y1);   
      return 1;  
     } 

     int xa, ya, xb, yb, xc, yc; // make 3 new triangles by connecting the midpoints of 
     xa = (x1 + x2)/2;    //. the previous triangle 
     ya = (y1 + y2)/2; 
     xb = (x1 + x3)/2; 
     yb = (y1 + y3)/2; 
     xc = (x2 + x3)/2; 
     yc = (y2 + y3)/2; 
     SeirpTri(g, x1, y1, xa, ya, xb, yb, n - 1, count++); // recursively call the function using the 3 triangles 
     SeirpTri(g, xa, ya, x2, y2, xc, yc, n - 1, count++); 
     SeirpTri(g, xb, yb, xc, yc, x3, y3, n - 1, count++); 
     return count; 
    } 

    public void paint(Graphics g)  
    { 
     int recursions = 3; 
     int count=1; 
     // call the recursive function sending in the number of recursions 
     SeirpTri(g, 319, 0, 0, 479, 639, 479, recursions, count); 

     // Counting triangles using math algorithm; 
     int count2 = 1; 
     if (recursions ==0) { 
      count2 =1; 
     } 
     else { 
      count2 = (int) Math.pow(3,(recursions-1)) * 3; 
     } 
     System.out.println("Correct answer is: " +count2); 
     System.out.println("Answer using recurvise is: " +count*3); 
    }   
} 
+0

대답 '무한대'아닌가
각 줄을 교체? :-) – Tenner

+0

수를 추적하기 위해 전역 정적 변수를 사용하는 것이 더 쉬울 수도 있습니다. – mellamokb

답변

1

당신은 count를 반환하지만, SeirpTri를 호출 한 결과를 보면 결코. 대신

: 당신은 모든 카운트 매개 변수가 필요하지 않습니다

return 
    SeirpTri(g, x1, y1, xa, ya, xb, yb, n - 1) 
    + SeirpTri(g, xa, ya, x2, y2, xc, yc, n - 1) 
    + SeirpTri(g, xb, yb, xc, yc, x3, y3, n - 1); 

:

SeirpTri(g, x1, y1, xa, ya, xb, yb, n - 1, count++); // recursively call the function using the 3 triangles 
SeirpTri(g, xa, ya, x2, y2, xc, yc, n - 1, count++); 
SeirpTri(g, xb, yb, xc, yc, x3, y3, n - 1, count++); 
return count; 

같은 뭔가를하려고합니다. 각 SeirpTri 호출은 삼각형과 그 "자식"(호출 트리상의)이 작성한 것을 알아야합니다. "루트"호출 (paint)은 총계를 반환합니다.

0

모든 매개 변수는 Java로 값에 의해 전달됩니다. 즉, count에 대한 변경 사항은 메소드에만 국한되며 상위 메소드에서 메소드에 전달 된 count 오브젝트는 변경하지 않습니다.
count 매개 변수를 반환하면이 문제를 해결할 수 있습니다. 부모 메소드에 count을 설정하기 만하면됩니다. 와

SeirpTri(...); 

:

count = SeirpTri(...); 
관련 문제