Created
October 24, 2016 15:17
-
-
Save thetamind/2555ecbad02a90fa4f6c2e994d21cf91 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Elixir
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
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