簡體   English   中英

使用遞歸創建分形圖案

[英]Creating fractal pattern using recursion

我正在嘗試使用遞歸創建此分形圖案。

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

我需要實現的功能是這樣的:

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);

    }

}

我的代碼輸出了應該輸出的內容,但空格數量不足。 我該如何解決?

模式包含2*N-1行。 我的方法是將模式分為兩半。 上半部分具有N條線,下半部分具有N-1條線。 下半部分只是上半部分的復制品,具有少一行和很少的額外空間(即N / 2個額外空間)。 因此,現在您只需要查找上半部分的模式。

要找到上半部分的圖案,請找到星數與具有行號的空格之間的關系。

我發現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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM