2012-04-02 16 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(...);