歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 沃爾夫勒姆自動機時空圖輸出 C語言實現

沃爾夫勒姆自動機時空圖輸出 C語言實現

日期:2017/3/1 9:16:43   编辑:Linux編程

沃爾夫勒姆自動機時空圖輸出 C語言實現

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>


//行寬度
#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;
}

運行效果:

Copyright © Linux教程網 All Rights Reserved