[英]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.