# セルオートマトン（１次元）

セルオートマトン

```nCell=201;nGen=100;
res=matrix(0,nrow=nGen,ncol=nCell)
res[1,ceiling(nCell/2)]=1;
for (i_gen in 2:nGen) {
temp.vec=c(res[i_gen-1,nCell],res[i_gen-1,],res[i_gen-1,1])
res[i_gen,]=(temp.vec[1:nCell]+temp.vec[2:(nCell+1)]+temp.vec[3:(nCell+2)])%%2;
}
# その1R（直感的に理解しやすい例）
for (i_gen in 2:nGen) {
for (i_cell in 2:(nCell-1)) {
res[i_gen,i_cell]=sum(res[i_gen-1,(i_cell-1):(i_cell+1)])%%2;
}
res[i_gen,1]=(res[i_gen-1,nCell]+res[i_gen-1,1]+res[i_gen-1,2])%%2;
res[i_gen,nCell]=(res[i_gen-1,(nCell-1)]+res[i_gen-1,nCell]+res[i_gen-1,1])%%2;
}
```

```dec2bin<-function(num, digits=8) {
bin=c()
if (num==0){
bin=0
} else {
while(num!=0){
rem=num%%2
num=num%/%2
bin=c(rem,bin)
}
}
if (length(bin) < digits){
res=matrix(0,nrow=1,ncol=digits)
res[(digits-length(bin)+1):digits]=bin
} else {res=bin}
return(res)
}

transFUN<-function(st,ruleID){
output=dec2bin(ruleID,8);
a=matrix(c(1,1,1,1,1,0,1,0,1,1,0,0,0,1,1,0,1,0,0,0,1,0,0,0),nrow=8,byrow=T)
newSt=output[which(apply(a,1,function(x) {all(x==st)}))]
return(newSt)
}
ECA<-function(nCell, nGen,ruleID){
res=matrix(0,nrow=nGen,ncol=nCell)
res[1,ceiling(nCell/2)]=1;
for (i_gen in 2:nGen) {
for (i_cell in 2:(nCell-1)) {
res[i_gen,i_cell]=transFUN(res[i_gen-1,(i_cell-1):(i_cell+1)],ruleID)
}
res[i_gen,1]=transFUN(c(res[i_gen-1,nCell],
res[i_gen-1,1],
res[i_gen-1,2]),ruleID)
res[i_gen,nCell]=transFUN(c(res[i_gen-1,(nCell-1)],
res[i_gen-1,nCell],
res[i_gen-1,1]),ruleID)
}
return(res)
}
# その2R （計算時間の改善はほぼなし）
ECA2<-function(nCell, nGen,ruleID){
res=matrix(0,nrow=nGen,ncol=nCell)
res[1,ceiling(nCell/2)]=1;
for (i_gen in 2:nGen) {
temp.mat=cbind(c(res[i_gen-1,nCell],res[i_gen-1,1:(nCell-1)]),res[i_gen-1,],
c(res[i_gen-1,2:nCell],res[i_gen-1,1]))
res[i_gen,]=apply(temp.mat,1,transFUN,ruleID)
}
return(res)
}
```