沃尔夫勒姆自动机时空图输出 C语言实现
#include
#include
#include
#include
//行宽度
#define ROW_LEN 38
//比特位域结构
typedef struct bits bits;
struct bits{
unsigned int c0 : 1;
unsigned int c1 : 1;
unsigned int c2 : 1;
unsigned int c3 : 1;
unsigned int c4 : 1;
unsigned int c5 : 1;
unsigned int c6 : 1;
unsigned int c7 : 1;
};
//行类型
typedef bits row[( ROW_LEN + 7 ) / 8];
//读取行中元胞
unsigned int get_cell( row rw, int x ){
unsigned int re = 0;
if( x < -1 || x > ROW_LEN ){
puts( "get_cell: 坐标错误." );
return re;
}
if( -1 == x ){
x = ROW_LEN - 1;
}
if( ROW_LEN == x ){
x = 0;
}
switch( x % 8 ){
case 0:{
re = rw[x / 8].c0;
}break;
case 1:{
re = rw[x / 8].c1;
}break;
case 2:{
re = rw[x / 8].c2;
}break;
case 3:{
re = rw[x / 8].c3;
}break;
case 4:{
re = rw[x / 8].c4;
}break;
case 5:{
re = rw[x / 8].c5;
}break;
case 6:{
re = rw[x / 8].c6;
}break;
case 7:{
re = rw[x / 8].c7;
}break;
}
return re;
}
//修改行中元胞
void set_cell( row rw, int x, unsigned int v ){
if( x < -1 || x > ROW_LEN ){
puts( "set_cell: 坐标错误." );
return;
}
if( -1 == x ){
x = ROW_LEN - 1;
}
if( ROW_LEN == x ){
x = 0;
}
v = v % 2;
switch( x % 8 ){
case 0:{
rw[x / 8].c0 = v;
}break;
case 1:{
rw[x / 8].c1 = v;
}break;
case 2:{
rw[x / 8].c2 = v;
}break;
case 3:{
rw[x / 8].c3 = v;
}break;
case 4:{
rw[x / 8].c4 = v;
}break;
case 5:{
rw[x / 8].c5 = v;
}break;
case 6:{
rw[x / 8].c6 = v;
}break;
case 7:{
rw[x / 8].c7 = v;
}break;
}
}
//演化行中元胞
unsigned int evo_cell( row rw, int x, unsigned char tab ){
unsigned char num = 0;
if( x < 0 || x > ROW_LEN - 1 ){
puts( "evo_cell: 坐标错误." );
return 0;
}
num |= ( unsigned char )get_cell( rw, x - 1 );
num <<= 1;
num |= ( unsigned char )get_cell( rw, x );
num <<= 1;
num |= ( unsigned char )get_cell( rw, x + 1 );
return ( tab >> num ) & 0x01;
}
//演化行到另外一个行
void evo_row( row rw1, row rw2, unsigned char tab ){
int x;
for( x = 0; x < ROW_LEN; x++ ){
set_cell( rw2, x, evo_cell( rw1, x, tab ) );
}
}
//随机初始化行
void rand_row( row rw ){
int x;
for( x = 0; x < ROW_LEN; x++ ){
set_cell( rw, x, rand() % 2 );
}
}
//显示行
void display_row( row rw ){
int x;
for( x = 0; x < ROW_LEN; x++ ){
printf( "%s", get_cell( rw, x ) ? "▉" : " " );
}
printf( "\n" );
}
//规则选择,这里选择为规则30,随机产生等腰三角形
//这种自动机是一种随机数算法的根基
#define TYPE_ID 30
//主函数
int main( int argc, char * argv[] ){
row rw1, rw2;
srand( ( unsigned int )time( NULL ) );
rand_row( rw1 );
while( 1 ){
display_row( rw1 );
_getch();
evo_row( rw1, rw2, TYPE_ID );
display_row( rw2 );
_getch();
evo_row( rw2, rw1, TYPE_ID );
}
return 0;
}
运行效果: