Skip to content

Instantly share code, notes, and snippets.

@timriffe
Forked from vvinichenko/life.r
Created February 24, 2012 09:50
Show Gist options
  • Save timriffe/1899814 to your computer and use it in GitHub Desktop.
Save timriffe/1899814 to your computer and use it in GitHub Desktop.
Game of Life in R (abdridged)
# Game of Life, by Vadim Vinichenko https://github.com/vvinichenko
# I've pasted his 2 functions here with no experiment at the bottom in order to be able to source this code
# straight from R like this:
# source("http://raw.github.com/gist/1899814/881e5f92c9413a5e1800c8a274d177982d796a8c/life2.r")
# that line loads the 2 functions automatically. Experiment Gist to follow
shiftMatrix <- function(mx, dr, dc) {
#Shift the matrix by dr (delta r) rows and dc columns
#by adding e.g. dr rows of zeros and removing dr rows from the other side
nr <- nrow(mx)
nc <- ncol(mx)
#If the matrix is shifted by more than its nrow or ncol, we get a matrix of zeros
if (abs(dr) >= nr || abs(dc) >= nc) {
mx <- matrix(0, nrow = nr, ncol = nc)
return(mx)
}
#Rows:
if (dr > 0) {
mx <- rbind(mat.or.vec(dr, nc), mx)
mx <- mx[1:nr,]
} else if (dr < 0) {
mx <- rbind(mx, mat.or.vec(-dr, nc))
mx <- mx[(1 - dr):(nr - dr),]
}
#Columns:
if (dc > 0) {
mx <- cbind(mat.or.vec(nr, dc), mx)
mx <- mx[,1:nc]
} else if (dc < 0) {
mx <- cbind(mx, mat.or.vec(nr, -dc))
mx <- mx[,(1 - dc):(nc - dc)]
}
return(mx)
}
life_cycle <- function(mx) {
#Move the board one generation forward
mx0 <- matrix(0, nrow = nrow(mx), ncol = ncol(mx))
#Produce 8 "shifted" boards and add them up
for (n in (-1:1)) {
for (m in (-1:1)) {
if (n !=0 || m !=0) {
mx0 <- mx0 + shiftMatrix(mx, n, m)
}
}
}
#Deaths and births
mx[mx0 > 3 | mx0 < 2] <- 0
mx[mx0 == 3] <- 1
return(mx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment