我正在尝试使用递归创建这个分形图案。
*
* *
*
* * * *
*
* *
*
* * * * * * * *
*
* *
*
* * * *
*
* *
*
我需要实现的功能是这样的:
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;
}
我想我做到了
void PrintLine(int n)
{
static int i = 0;
if(n & 1)
{
for(int j = 0; j < i; j++)
{
cout << ' ';
}
cout << "*\n";
}
else if(i > n)
{
for(int j = 0; j < i - 1; j++)
{
cout << ' ';
}
for(int j = 0; j < n; j++)
{
cout << "* ";
}
cout << "\n";
}
else
{
for(int j = 0; j < n; j++)
{
cout << "* ";
}
cout << "\n";
}
i++;
}
void pattern(int n)
{
if(n <= 1)
{
PrintLine(1);
return;
}
pattern(n / 2);
PrintLine(n);
pattern(n / 2);
}