Skip to content

Instantly share code, notes, and snippets.

@thetamind
Created October 24, 2016 15:17
Show Gist options
  • Save thetamind/2555ecbad02a90fa4f6c2e994d21cf91 to your computer and use it in GitHub Desktop.
Save thetamind/2555ecbad02a90fa4f6c2e994d21cf91 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Elixir
defmodule ConwayTest do
use ExUnit.Case
# The Rules
# For a space that is 'populated':
# Each cell with one or no neighbors dies, as if by solitude.
# Each cell with four or more neighbors dies, as if by overpopulation.
# Each cell with two or three neighbors survives.
# For a space that is 'empty' or 'unpopulated'
# Each cell with three neighbors becomes populated.
test "gen_interesting" do
world = [{1,1}, {1,2}, {1,3}]
assert world != world |> gen_interesting
assert world = world |> gen_interesting |> gen_interesting
end
def gen_interesting(cells) do
cfilter = fn ({cell, cnt}) ->
case cnt do
3 -> true
2 -> Enum.member?(cells, cell)
_ -> false
end
end
cells
|> Enum.map(&neighbours/1)
|> Enum.concat
|> Enum.group_by(&(&1))
|> Enum.map(fn ({x,xs}) -> {x, Enum.count xs} end)
|> Enum.filter(cfilter)
|> Enum.map(fn {x, _} -> x end)
end
def neighbours({x,y}) do
for i <- (-1..1), j <- (-1..1), i != 0 || j != 0, do: {x+i, y+j}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment