Skip to content

Instantly share code, notes, and snippets.

@thara
Last active April 8, 2020 14:55
Show Gist options
  • Save thara/f01d276eb19dac5580c3096748d7cb76 to your computer and use it in GitHub Desktop.
Save thara/f01d276eb19dac5580c3096748d7cb76 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Elixir
defmodule LifeGame do
def advance(board) do
board |> neighbors_all |> MapSet.to_list |> Enum.filter(&living?(&1, board)) |> MapSet.new
end
defp living?(point, board) do
count = point |> neighbors |> Enum.count(&MapSet.member?(board, &1))
count == 3 || (MapSet.member?(board, point) && count == 2)
end
defp neighbors_all(board) do
MapSet.union(board, MapSet.new(Enum.flat_map(board, &neighbors/1)))
end
defp neighbors(point) do
{x, y} = point
[
{x + 1, y},
{x - 1, y},
{x, y + 1},
{x, y - 1},
{x + 1, y + 1},
{x + 1, y - 1},
{x - 1, y + 1},
{x - 1, y - 1},
]
end
end
print_board = fn state ->
Enum.map(0..10, fn y ->
Enum.map(0..10, fn x ->
if MapSet.member?(state, {x, y}) do
"*"
else
"-"
end
end)
end) |> Enum.join("\n")
end
state = [{0, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}] |> MapSet.new
print_board.(state) |> IO.puts
0..100 |> Enum.reduce(state, fn _, state ->
Process.sleep(500)
IO.puts("\u{1b}[15A\r")
new_state = state |> LifeGame.advance
new_state |> print_board.() |> IO.puts
new_state
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment