Skip to content

Instantly share code, notes, and snippets.

@mwormleonhard
Last active August 29, 2015 13:57
Show Gist options
  • Save mwormleonhard/9818274 to your computer and use it in GitHub Desktop.
Save mwormleonhard/9818274 to your computer and use it in GitHub Desktop.
Conway
new.empty.grid <- function(size=1000) {
return(matrix(data=0, nrow=size, ncol=size))
}
new.random.grid <- function(size=1000) {
return(matrix(data=sample(c(0,1), size^2, replace=TRUE), nrow=size, ncol=size))
}
iterate <- function(inputmatrix) {
nextgen <- inputmatrix
for(i in 1:nrow(inputmatrix)) {
for(j in 1:ncol(inputmatrix)) {
rowcoords <-max(i-1,1):min(i+1,nrow(inputmatrix))
colcoords <-max(j-1,1):min(j+1,ncol(inputmatrix))
if(inputmatrix[i,j]==0 & sum(inputmatrix[rowcoords,colcoords])==3) {
nextgen[i,j] <- 1
}
if(inputmatrix[i,j]==1 &
!(sum(inputmatrix[rowcoords,colcoords])==3 ||
sum(inputmatrix[rowcoords,colcoords])==4) ) {
nextgen[i,j] <- 0
}
}
}
return(nextgen)
}
#main
sz <- 100
t <- new.random.grid(sz)
png()
for(k in 1:1000) {
image(t, asp=1, axes=F, col=c("white", "black"))
t <- iterate(t)
}
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment