Last active
December 20, 2016 15:25
-
-
Save simonewebdesign/ede2ec800acdf1d81bbc0b914f76b2b5 to your computer and use it in GitHub Desktop.
functional game of life — from http://beyondscheme.com/2016/distributed-game-of-life-in-elixir#comment-2721697256
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
def calc_next_grid(grid) do | |
Enum.reduce(alive_plus_neighbors(grid), MapSet.new, fn({x, y}, grid2) -> | |
is_alive = MapSet.member?(grid, {x, y}) | |
num_neighbors = count_neighbors(grid, {x, y}) | |
if should_live?(is_alive, num_neighbors) do | |
MapSet.put(grid2, {x, y}) | |
else | |
grid2 | |
end | |
end) | |
end | |
defp alive_plus_neighbors(grid) do | |
offsets = [{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}] | |
Enum.reduce(grid, MapSet.new, fn({x, y}, grid2) -> | |
Enum.reduce(offsets, grid2, fn({x_off, y_off}, grid3) -> | |
MapSet.put(grid3, {x + x_off, y + y_off}) | |
end) | |
end) | |
end | |
defp should_live?(is_alive, num_neighbors) do | |
(num_neighbors == 2 && is_alive) || (num_neighbors == 3) | |
end | |
defp count_neighbors(grid, {x, y}) do | |
offsets = [{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}] | |
Enum.reduce(offsets, 0, fn({x_off, y_off}, acc) -> | |
acc + if MapSet.member?(grid, {x + x_off, y + y_off}), do: 1, else: 0 | |
end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment