2016-10-26 36 views
0

再帰を使用してこのフラクタルパターンを作成しようとしています。再帰を使用してフラクタルパターンを作成する

* 
* * 
    * 
* * * * 
    * 
    * * 
     * 
* * * * * * * * 
     * 
     * * 
      * 
     * * * * 
      * 
      * * 
       * 

私が実装する必要がある機能はこれです:

void pattern(ostream& outs, unsigned int n, unsigned int i); 
// Precondition: n is a power of 2 greater than zero. 
// Postcondition: A pattern based on the above example has been 
// printed to the ostream outs. The longest line of the pattern has 
// n stars beginning in column i of the output. For example, 
// The above pattern is produced by the call pattern(cout, 8, 0). 

これまでのところ、これは私が持っているものです。

void pattern(ostream& outs, unsigned int n, unsigned int i){ 

    if (n == 1){ 
     outs << "*"<<endl; 
    } 

    else{ 
     pattern(outs, n/2, i + 1); 
     for (int k = 0; k < n; k++){ 
      outs << "* "; 

     } 
     outs<<endl; 


     for (int k = 0; k < i; k++){ 
      outs << ' '; 
     } 

     pattern(outs, n/2, i + 1); 

    } 

}

私のコードはどうあるべきかを出力スペースは空白になります。どうすれば修正できますか?

+1

@ c650どのようなヒントがあれば、私を始められますか? – user2896120

+0

それは2のべき乗でなければならないと言いますので、あなたは 'パターン(外、n-1、i + 1);を間違って考えているかもしれません。 – Charles

+0

ようこそStackOverflowへ。ヘルプドキュメントの投稿ガイドラインを読み、それに従ってください。 [最小、完全で検証可能な例](http://stackoverflow.com/help/mcve)がここに適用されます。コードを投稿して問題を正確に記述するまでは、効果的にお手伝いすることはできません。 StackOverflowは、コーディングまたはチュートリアルサービスではありません。 – Prune

答えて

1

パターンには、2*N-1行が含まれています。私のアプローチは、パターンを2つの半分に分割することです。上半分はNの線を有し、下半分はN-1線を有する。下半分は、行が1つ少なく、追加のスペースが少ない上半分のレプリカです(つまり、N/)。だから上半身のみのパターンを見つけなければなりません。

上半分のパターンを見つけるには、星の数と行番号のスペースの関係を見つけます。私はN=8

LineNumber Stars Spaces 
    1   1  0 
    2   2  0 
    3   1  1 
    4   4  0 
    5   1  2 
    6   2  2 
    7   1  3 
    8   8  0 
    9   1  4 
    10  2  4 
    11  1  5 
    12  4  4 
    13  1  6 
    14  2  6 
    15  1  7 

見つかり

は、あなたが今、上記の例を見て、パターンを見つけることを願っています。そうでない場合は、spacesを下記のコードで参照することができます。

#include <iostream> 
#include <cmath> 
using namespace std; 
bool PowerOfTwo(int n) 
{ 
    if ((n&(n-1)) == 0 && n!=1) 
     return true; 
    return false; 
} 
int star(int n) 
{ 
    int i=n,ans=0; 
    while(i%2==0) 
    { 
     i/=2; 
     ans++; 
    } 
    return pow(2,ans); 
} 
int spaces(int n) 
{ 
    if(PowerOfTwo(n)==true) 
     return 0; 
    return (n-1)/2; 
} 
void printpattern(int n) 
{ 
    int i,sp,st; 
    sp = spaces(n); 
    for(i=1;i<=sp;i++) 
     cout<<" "; 
    st = star(n); 
    for(i=1;i<=st;i++) 
     cout<<"* "; 
} 
void pattern(int n) 
{ 
    int i,j,sp; 
    for(i=1;i<=n;i++)    //Upper Half  
    { 
     printpattern(i); 
     cout<<endl; 
    } 
    sp = n/2; 
    for(i=1;i<=n-1;i++)    //Lower Half 
    { 
     for(j=1;j<=sp;j++) 
      cout<<" "; 
     printpattern(i); 
     cout<<endl; 
    } 
} 
int main() 
{ 
    int n=8; 
    pattern(n); 
    return 0; 
} 
関連する問題