Created
October 24, 2013 19:10
-
-
Save cjbayesian/7143216 to your computer and use it in GitHub Desktop.
Functions for simulating Conway's Game of Life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Functions for simulating Conway's Game of Life | |
## Modified from http://www.petrkeil.com/?p=236 | |
neighbour_count <- function(X) | |
{ | |
side <- nrow(X) | |
# make the shifted copies of the original array | |
allW = cbind( rep(0,side) , X[,-side] ) | |
allNW = rbind(rep(0,side),cbind(rep(0,side-1),X[-side,-side])) | |
allN = rbind(rep(0,side),X[-side,]) | |
allNE = rbind(rep(0,side),cbind(X[-side,-1],rep(0,side-1))) | |
allE = cbind(X[,-1],rep(0,side)) | |
allSE = rbind(cbind(X[-1,-1],rep(0,side-1)),rep(0,side)) | |
allS = rbind(X[-1,],rep(0,side)) | |
allSW = rbind(cbind(rep(0,side-1),X[-1,-side]),rep(0,side)) | |
# summation of the matrices | |
X2 <- allW + allNW + allN + allNE + allE + allSE + allS + allSW | |
} | |
GOL <- function(X,delta,plt=TRUE) | |
{ | |
if(plt) | |
par(mfrow=c(1,2),pty='s') | |
alive_prop <- numeric(delta) | |
for (i in 1:delta) | |
{ | |
alive_prop[i] <- sum(X/prod(dim(X))) | |
if(plt) | |
{ | |
image(X,main=i,col=0:1,xaxt='n',yaxt='n') | |
plot(1:i,alive_prop[1:i], | |
ylim=c(0,0.1), | |
type='l', | |
lwd=2, | |
ylab='Proportion alive', | |
xlab='Time') | |
} | |
X2 <- neighbour_count(X) | |
X3 <- X | |
# the rules of GoL are applied using logical subscripting | |
X3[X==0 & X2==3] <- 1 | |
X3[X==1 & X2<2] <- 0 | |
X3[X==1 & X2>3] <- 0 | |
X <- X3 | |
} | |
return(X) | |
} | |
## Example: | |
grd_size <- 100 | |
## Random starting grid: | |
x <- array(sample(1:0,grd_size^2,replace=T,prob=c(0.1,0.9)), | |
dim=c(grd_size,grd_size)) | |
## Run GOL 1000 time steps | |
end = GOL(X=x,delta=1000) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment