啊,这题没有做出来, 这两天吃不好,睡不好。
那天,我用循环的方法做好很长时间都没有做出来,后来灵光一闪,用位运算来做应该要简单些,于是,牺牲了两天的所有休息时间,并复习了递归n次,终于有了下面的代码。
一个人鼓捣了好几天,工作一空就又泡在这代码里,两天都没有学习新东西了。今天终于可以休息一会了!
说来还是羞愧,下面这代码,调试了很时间,有些特殊数据(代码中的if(0==(cnt++/6)%2)语句中的6,不是我推算出来的。而是我在多次测试结果中找出来的一个规律数。为什么要用6?我不知道
![](images/smilies/emot/em13.gif)
。)
算法不好(我不是直接排列出结果,我是排列出所有结果,再过滤出不用的结果),只是算出了结果。不过,自己鼓励自己说,总算是自己写的吧。
![](zzz/editor/img/code.gif)
程序代码:
#include <stdio.h>
#include <iostream>
using namespace std;
const int SIZE(4); //结果个数为 (SIZE-2)个
int count_motrix=0;//矩阵计数器
int arr[SIZE];
void initia()//初始化数组
{
for(int cnt=0;cnt<SIZE;cnt++)
{
if (0==cnt) arr[cnt]=1;
else arr[cnt]=arr[cnt-1]*2;
}
for(int cnt=3;cnt<SIZE;cnt=cnt+4) arr[cnt]=0;
}
void bina_out_line(int _in_num)
{
for(int cnt=0;cnt<SIZE;cnt++)
{
bool tem_bt = _in_num & (1<<cnt ) ;
cout << " " << tem_bt ;//put 0 or 1
}
cout << endl ; //There is an "endl" at the end of a line.
}
bool test()//过滤
{
for (int i=0;i<SIZE;i++)
{
if ( 0==(i+1)%4 ) //if on 4/8/12...
{
if( 0 != arr[i] ) return false;//如果值不为0 不打印
else continue; //如果值为0 可能要打印
}
if(0==arr[i]) return false;
}
return true;
}
inline void swapit(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void perm(int arr[], int k, int m)
{ static int cnt=0;
int i;
if (k == m)
{
if( test() )
{
if(0==(cnt++/6)%2)
{
cout << "counter:" << ++count_motrix << endl;
for (i = 0; i <= m; i++)
bina_out_line( arr[i] ); //cout << (arr[i])<< ","; //
cout << "\n";
}
}
}
else
for (i=k; i <= m; i++)
{
swapit (arr[k], arr[i]);
perm (arr, k+1, m);
swapit (arr[k], arr[i]);
}
}
int main()
{ freopen("result.txt", "w", stdout);
initia();
perm(arr, 0,SIZE-1);
return 0;
}