Skip to content

Instantly share code, notes, and snippets.

@fffej
Last active November 10, 2015 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fffej/720b2da0462067b7ee1e to your computer and use it in GitHub Desktop.
Save fffej/720b2da0462067b7ee1e to your computer and use it in GitHub Desktop.
Game of Life in R
# Game of life. Based on a matrix representation with cells being in either
# alive (1) or dead (0) state.
nextStep <- function(grid) {
w = ncol(grid)
h = nrow(grid)
out = matrix(0,nrow=h,ncol=w)
for (i in 1:w) {
for (j in 1:h) {
n = neighbours(grid,i,j)
s = grid[i,j]
if (s == 1 && n < 2)
out[i,j] = 0 #under-population
else if (s == 1 && (n == 2 || n == 3))
out[i,j] = 1 #survices
else if (s == 1 && n > 3)
out[i,j] = 0 #over population
else if (s == 0 && n == 3)
out[i,j] = 1 # reproduction
}
}
out
}
# A count of the live neighbours
neighbours <- function(g,x,y) {
mc = max(1,x-1)
mr = max(1,y-1)
bc = min(x+1,ncol(g))
br = min(y+1,nrow(g))
# Just sum the bounds and remember to take away self!
sum(c(g[mc:bc,mr:br])) - g[x,y]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment