Skip to content

Instantly share code, notes, and snippets.

@rickhull
Created December 19, 2014 18:42
Show Gist options
  • Save rickhull/a0bd4fcf724cc08d9637 to your computer and use it in GitHub Desktop.
Save rickhull/a0bd4fcf724cc08d9637 to your computer and use it in GitHub Desktop.
actual impl
defmodule ConwayDeathmatch do
def new(x_len, y_len) when is_integer(x_len) and x_len > 0 and is_integer(y_len) and y_len > 0 do
new_grid(x_len, y_len, fn(_, _) -> 0 end)
end
def dim(grid) when is_tuple(grid) do
{grid |> tuple_size, grid |> elem(0) |> tuple_size}
end
def cell(grid, x, y) do
grid |> elem(x) |> elem(y)
end
def tick(grid) do
{x,y} = dim(grid)
new_grid(x, y, &next_cell(grid, &1, &2))
end
def populate(grid, points) when is_tuple(grid) and is_tuple(points) do
{x,y} = dim(grid)
new_grid(x, y, &in_points?(points, &1, &2))
end
defp in_points?(points, x, y) do
points |> Enum.any?(fn(point) -> {x,y} == point end)
end
def next_cell(grid, x, y) do
case {cell(grid, x, y), neighbors(grid, x, y) |> alive_neighbors} do
{0, 3} -> 1
{0, _} -> 0
{_, 2} -> 1
{_, 3} -> 1
{_, _} -> 0
end
end
# def translate(points) do
# t = {}
# points |> Enum.each
# end
# count of neighbors which aren't dead (0)
def alive_neighbors(list) when is_list(list) do
list |> Enum.count(fn(x) -> x != 0 end)
end
def toroidal(x, x_len) when is_integer(x) and is_integer(x_len) and x_len > 0 do
case rem(x, x_len) do
r when r >= 0 ->
r
r ->
r + x_len
end
end
def neighbors(grid, x, y) when is_tuple(grid) and is_integer(x) and is_integer(y) do
{x_len, y_len} = dim(grid)
for xn <- (x-1)..(x+1) do
xt = toroidal(xn, x_len)
for yn <- (y-1)..(y+1) do
yt = toroidal(yn, y_len)
if x != xt or y != yt, do: cell(grid, x, y)
end |> Enum.reject(&is_nil/1)
end |> List.flatten
end
# creates new grid according populated according to fun
defp new_grid(x_len, y_len, fun) when is_function(fun) and is_integer(x_len) and is_integer(y_len) and x_len > 0 and y_len > 0 do
for y <- 0..(y_len - 1) do
for x <- 0..(x_len - 1) do
fun.(x, y)
end
end |> Enum.map(&List.to_tuple/1) |> List.to_tuple
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment