# 基礎実習　B02

```bin2dec <- function(bin){
# convert binary to decimal
b.rev = rev(bin)
ones = which(b.rev == 1)
dec = sum(b.sq)
return(dec)
}

dec2bin <- function(dec, digit) {
# convert decimal to binary
bin = rep(0, digit)
r.counter  = 1
while(dec != 0){
r = dec %% 2
dec = dec %/% 2
bin[r.counter] = r
r.counter = r.counter + 1
}
return(rev(bin))
}

# cellur automata
# RULE 150
time = 100
n.cells =  101
cells = matrix(0, nrow = time, ncol = n.cells)
state = rep(0,n.cells)
state[51] = 1
cells[1,] = state
for (i.time in 2:time) {
left = c(state[n.cells], state[1:(n.cells - 1)])
right = c(state[2:n.cells], state[1])
s = left + state + right
state = s %% 2
cells[i.time, ] = state
}

time = 100
n.cells =  101
cells = matrix(0, nrow = time, ncol = n.cells)
cells[1,51] = 1
for (i.time in 2:time) {
left = c(cells[(i.time-1), n.cells], cells[(i.time-1), 1:(n.cells - 1)])
right = c(cells[(i.time-1), 2:n.cells], cells[(i.time-1), 1])
s = left + cells[(i.time-1),] + right
cells[i.time, ] = s %% 2
}

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)
}
res<-ECA(200,100,99)
image(res)

```