Skip to content

Instantly share code, notes, and snippets.

@fffej fffej/GameOfLife.R
Last active Nov 10, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.