1.位运算法
2.普通算法
这里主要介绍一下普通算法
例如,在枚举0~64的二进制数的时候,可以通过对2取模再除2的方法,类似于二进制数和十进制数之间的转换。见如下代码:
#include<iostream>
using namespace std;
int c[100];
void fun(int n)
{
for (int i = 0; i < 6; i++)
{
c[i] = n % 2;
n /= 2;
}
}
int main()
{
for (int n = 0; n < 64; n++)
{
fun(n);
for (int j = 0; j < 6; j++)
cout << c[j] << " ";
cout << endl;
}
return 0;
}
运行出的结果为
/*
0 0 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
0 0 1 0 0 0
1 0 1 0 0 0
0 1 1 0 0 0
1 1 1 0 0 0
0 0 0 1 0 0
1 0 0 1 0 0
0 1 0 1 0 0
1 1 0 1 0 0
0 0 1 1 0 0
1 0 1 1 0 0
0 1 1 1 0 0
1 1 1 1 0 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 0 0 1 0
1 1 0 0 1 0
0 0 1 0 1 0
1 0 1 0 1 0
0 1 1 0 1 0
1 1 1 0 1 0
0 0 0 1 1 0
1 0 0 1 1 0
0 1 0 1 1 0
1 1 0 1 1 0
0 0 1 1 1 0
1 0 1 1 1 0
0 1 1 1 1 0
1 1 1 1 1 0
0 0 0 0 0 1
1 0 0 0 0 1
0 1 0 0 0 1
1 1 0 0 0 1
0 0 1 0 0 1
1 0 1 0 0 1
0 1 1 0 0 1
1 1 1 0 0 1
0 0 0 1 0 1
1 0 0 1 0 1
0 1 0 1 0 1
1 1 0 1 0 1
0 0 1 1 0 1
1 0 1 1 0 1
0 1 1 1 0 1
1 1 1 1 0 1
0 0 0 0 1 1
1 0 0 0 1 1
0 1 0 0 1 1
1 1 0 0 1 1
0 0 1 0 1 1
1 0 1 0 1 1
0 1 1 0 1 1
1 1 1 0 1 1
0 0 0 1 1 1
1 0 0 1 1 1
0 1 0 1 1 1
1 1 0 1 1 1
0 0 1 1 1 1
1 0 1 1 1 1
0 1 1 1 1 1
1 1 1 1 1 1
*/
#include<iostream>
#include<cmath>
using namespace std;
int a[5][6];
int b[5][6];
int c[5][6];
void fun(int n)
{
for (int i = 0; i < 6; i++)
{
c[0][i] = n % 2;
n /= 2;
}
}
void set(int i, int j)
{
b[i][j] = b[i][j] ^ 1;//取反
if (i - 1 >= 0) b[i - 1][j] = b[i - 1][j] ^ 1;
if (i + 1 < 5) b[i + 1][j] = b[i + 1][j] ^ 1;
if (j - 1 >= 0) b[i][j - 1] = b[i][j - 1] ^ 1;
if (j + 1 < 6) b[i][j + 1] = b[i][j + 1] ^ 1;
}
int main()
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 6; j++)
cin >> a[i][j];
for (int n = 0; n < 64; n++)
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 6; j++)
{
c[i][j] = 0;
b[i][j] = a[i][j];
}
fun(n);//枚举
for (int j = 0; j < 6; j++)//第0行
if (c[0][j] == 1) set(0, j);
for (int i = 1; i < 5; i++)//第1~4行
for (int j = 0; j < 6; j++)
{
if (b[i - 1][j] == 1)
{
set(i, j);
c[i][j] = 1;
}
}
int flag = 1;//对末行检验
for (int j = 0; j < 6; j++)
{
if (b[4][j] == 1)
{
flag = 0;
break;
}
}
if (flag == 1)
break;
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 6; j++)
cout << c[i][j] << " ";
cout << endl;
}
return 0;
}