Last active
November 10, 2015 06:47
-
-
Save fffej/720b2da0462067b7ee1e to your computer and use it in GitHub Desktop.
Game of Life in R
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
# 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