Created
February 27, 2024 16:28
-
-
Save jrosell/dcf222b4a0ee28aaf4303d2507051cf1 to your computer and use it in GitHub Desktop.
Game of Life using {coro} generators 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 using {coro} generators in R | |
# Inspiration from Jack Diederich's Python implementation: https://gist.github.com/jhrr/2b5a60e9efcb573c9cc4 | |
library(tidyverse) | |
library(coro) | |
library(zeallot) | |
generate_neighbors <- generator(function(point) { | |
c(x, y) %<-% point | |
yield(c(x + 1, y)) | |
yield(c(x - 1, y)) | |
yield(c(x, y + 1)) | |
yield(c(x, y - 1)) | |
yield(c(x + 1, y + 1)) | |
yield(c(x + 1, y - 1)) | |
yield(c(x - 1, y + 1)) | |
yield(c(x - 1, y - 1)) | |
}) | |
recalculate <- \(board) { | |
board %>% | |
map(generate_neighbors) %>% | |
map(collect) %>% | |
unlist(recursive = FALSE) %>% | |
union(board) | |
} | |
advance <- \(board){ | |
newstate <- list() | |
for(point in recalculate(board)) { | |
point_neighbors <- collect(generate_neighbors(point)) | |
count <- sum(point_neighbors %in% board) | |
if (count == 3 || (count == 2 && (list(point) %in% board))) { | |
newstate <- c(newstate, list(point)) | |
} | |
} | |
return(newstate) | |
} | |
glider <- list(c(0,0), c(1,0), c(2, 0), c(0,1), c(1,2)) | |
for(i in 1:1000){ | |
glider <- advance(glider) | |
print(paste0(i, " ", paste(glider, collapse = ", "))) | |
} | |
# [1] "1000 c(-249, -248), c(-249, -250), c(-250, -250), c(-248, -250), c(-250, -249)" | |
is_equivalent_set <- \(lst_x, lst_y) { | |
ocurrences <- | |
lst_x |> | |
sapply(\(x) { | |
lst_y |> sapply(\(y) identical(sort(x), sort(y))) | |
}) | |
return(all(rowSums(ocurrences) > 0) & all(colSums(ocurrences) > 0)) | |
} | |
glider_p <- list(c(-249, -250), c(-248, -250), c(-250, -250), c(-249, -248), c(-250, -249)) | |
is_equivalent_set(glider, glider_p) | |
# TRUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment