昔,BASIC で組んで喜んでいたものだ
10分ほどで組んで,チューニング
for を使っているけど,速すぎる。
ただ,図を描くのは一気呵成でないといけないので,rect で引数にベクトルを与えた。
life <- function(xy, step = 100, nrow = 100, ncol = nrow, sleep = 0) {
a <- matrix(0, nrow, ncol)
a[xy] <- 1
nrow1 <- nrow - 1
ncol1 <- ncol - 1
old <- par(mar = c(0, 0, 0, 0))
for (l in seq_len(step)) {
b <- a
plot(1, 1, type = "n", xlim = c(1, nrow), ylim = c(1, ncol), bty = "n", axes = FALSE, xlab = "", ylab = "")
i0 <- j0 <- numeric(nrow * ncol)
n <- 0
for (i in 2:nrow1) {
for (j in 2:ncol1) {
if (a[i, j] == 0 && sum(a[(i - 1):(i + 1), (j - 1):(j + 1)]) == 3) {
b[i, j] <- 1
} else if (a[i, j] == 1 && (sum(a[(i - 1):(i + 1), (j - 1):(j + 1)]) <= 2 || sum(a[(i - 1):(i + 1), (j -
1):(j + 1)]) >= 5)) {
b[i, j] <- 0
}
if (b[i, j]) {
n <- n + 1
i0[n] <- i
j0[n] <- j
}
}
}
i0 <- i0[1:n]
j0 <- j0[1:n]
rect(i0 - 0.5, j0 - 0.5, i0 + 0.5, j0 + 0.5, col = "red", border = "red")
Sys.sleep(sleep)
a <- b
}
par(old)
}
x <- rbind(cbind(rep(49, 11), 45:55), cbind(rep(50, 11), 45:55), cbind(rep(51, 11), 45:55))
life(x, step = 25)
x <- cbind(sample(100, 5000, replace = TRUE), sample(100, 5000, replace = TRUE))
life(x, step = 400)
x <- matrix(c(18, 11, 18, 29, 18, 30, 18, 31, 19, 12, 19, 29, 20, 10, 20, 11, 20, 12, 20, 31), byrow = TRUE, ncol = 2)
life(x + 30, step = 200)