我最近使用内置的C控制台进行了一个简单的基本元胞自动机可视化,活的细胞是@
,死的细胞是空间,但由于某种原因,无论哪个规则集,它都会向控制台显示一些随机输出,似乎有效的是简单的规则集,如规则2。我还不知道是什么原因造成了这个问题。
代码:
int gen[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ruleset[]={0,0,0,0,0,0,1,0};
int size = sizeof gen / sizeof gen[0];
int alive=1;
int dead=0;
int rules(int a, int b, int c){
if(a==1 && b==1 && c==1){return ruleset[0];}
if(a==1 && b==1 && c==0){return ruleset[1];}
if(a==1 && b==0 && c==1){return ruleset[2];}
if(a==1 && b==0 && c==0){return ruleset[3];}
if(a==0 && b==1 && c==1){return ruleset[4];}
if(a==0 && b==1 && c==0){return ruleset[5];}
if(a==0 && b==0 && c==1){return ruleset[6];}
if(a==0 && b==0 && c==0){return ruleset[7];}
}
int main(void){
int iterations;
int procces;
for(iterations=0;iterations<100;iterations++){
for(procces=0;procces<size;procces++){
int left=gen[procces-1];
int right=gen[procces+1];
int cell=gen[procces];
gen[procces]=rules(left,cell,right);
if(gen[procces]==0){
printf(" ");
}
else{
printf("@");
}
}
printf("n");
}
}
我引入了一个函数,该函数避免了名为get_gen()
的超范围下标。
这一个假设你的数组之外的所有东西都是贫瘠的0。
根据你的规则,活细胞向左"移动",然后在贫瘠的边缘从world
中掉出来。
正如其他人指出的那样,你可以在戒指上执行死刑。当模式扩展到给定的空间之外时,您甚至可以编写一个扩展世界的版本。
#include <stdio.h>
int gen[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ruleset[]={0,0,0,0,0,0,1,0};
int size = sizeof gen / sizeof gen[0];
int alive=1;
int dead=0;
int rules(int a, int b, int c){
if(a==1 && b==1 && c==1){return ruleset[0];}
if(a==1 && b==1 && c==0){return ruleset[1];}
if(a==1 && b==0 && c==1){return ruleset[2];}
if(a==1 && b==0 && c==0){return ruleset[3];}
if(a==0 && b==1 && c==1){return ruleset[4];}
if(a==0 && b==1 && c==0){return ruleset[5];}
if(a==0 && b==0 && c==1){return ruleset[6];}
if(a==0 && b==0 && c==0){return ruleset[7];}
}
int get_gen(int pos,int *gen,int sz){
if(pos<0 || pos>=sz){
return 0;
}
return gen[pos];
}
int main(void){
int iterations;
int procces;
for(iterations=0;iterations<100;iterations++){
for(procces=0;procces<size;procces++){
int left=get_gen(procces-1,gen,size);
int right=get_gen(procces+1,gen,size);
int cell=get_gen(procces,gen,size);
gen[procces]=rules(left,cell,right);
if(gen[procces]==0){
printf(" ");
} else {
printf("@");
}
}
printf("n");
}
}