/
cell.ex
48 lines (39 loc) · 1.4 KB
/
cell.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
defmodule GameOfLife.Cell do
def keep_alive?(alive_cells, {x, y} = _alive_cell) do
case count_neighbours(alive_cells, x, y, 0) do
2 -> true
3 -> true
_ -> false
end
end
def become_alive?(alive_cells, {x, y} = _dead_cell) do
3 == count_neighbours(alive_cells, x, y, 0)
end
def dead_neighbours(alive_cells) do
neighbours = neighbours(alive_cells, [])
(neighbours |> Enum.uniq) -- alive_cells
end
defp neighbours([{x, y} | cells], neighbours) do
neighbours(cells, neighbours ++ [
{x - 1, y - 1}, {x , y - 1}, {x + 1, y - 1},
{x - 1, y }, {x + 1, y },
{x - 1, y + 1}, {x , y + 1}, {x + 1, y + 1}
])
end
defp neighbours([], neighbours), do: neighbours
defp count_neighbours([head_cell | tail_cells], x, y, count) do
increment = case head_cell do
{hx, hy} when hx == x - 1 and hy == y - 1 -> 1
{hx, hy} when hx == x and hy == y - 1 -> 1
{hx, hy} when hx == x + 1 and hy == y - 1 -> 1
{hx, hy} when hx == x - 1 and hy == y -> 1
{hx, hy} when hx == x + 1 and hy == y -> 1
{hx, hy} when hx == x - 1 and hy == y + 1 -> 1
{hx, hy} when hx == x and hy == y + 1 -> 1
{hx, hy} when hx == x + 1 and hy == y + 1 -> 1
_not_neighbour -> 0
end
count_neighbours(tail_cells, x, y, count + increment)
end
defp count_neighbours([], _x, _y, count), do: count
end