Skip to content

Instantly share code, notes, and snippets.

@aaronwolen
Created April 10, 2015 17:37
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 aaronwolen/0c5cf9d8e829e9656958 to your computer and use it in GitHub Desktop.
Save aaronwolen/0c5cf9d8e829e9656958 to your computer and use it in GitHub Desktop.
Simple R implementation of cellular automata described in A New Kind of Science.
# A few simple rules from Stephen Wolfram's A New Kind of Science
apply_rule <- function(x, rule = "254") {
stopifnot(length(x) == 3)
stopifnot(all(x %in% c(0, 1)))
rules <- list("254" = c(1, 1, 1, 1, 1, 1, 1, 0),
"250" = c(1, 1, 1, 1, 1, 0, 1, 0),
"90" = c(0, 1, 0, 1, 1, 0, 1, 0),
"30" = c(0, 0, 0, 1, 1, 1, 1, 0))
rule <- setNames(rules[[rule]],
c("111", "110", "101", "100", "011", "010", "001", "000"))
rule[paste(x, collapse = "")]
}
ncols <- 500
rule <- "30"
x <- matrix(0, ncol = ncols + 1, nrow = ncols / 2)
x[1, ncols / 2 + 1] <- 1
for (i in 1:nrow(x)) {
if (i == nrow(x)) break
newrow <- mapply(function(j1, j2) apply_rule(x[i, j1:j2], rule),
j1 = 1:(ncol(x) - 2), j2 = 3:ncol(x))
x[i + 1,] <- c(0, newrow, 0)
}
image(t(x)[, nrow(x):1], col = c("white", "black"), axes = FALSE)
grid(ncol(x), nrow(x), lty = 1)
box(col = "lightgray")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment