Skip to content

Instantly share code, notes, and snippets.

@wende
Last active July 31, 2016 10:46
Show Gist options
  • Save wende/7ee924f5ba8314469d242ef6f1ba65d1 to your computer and use it in GitHub Desktop.
Save wende/7ee924f5ba8314469d242ef6f1ba65d1 to your computer and use it in GitHub Desktop.
module GameOfLife where
import [Enum, Access]
neighbours(x,y, state) ->
[{nx, ny} || nx <- -1..1, ny <- -1..1]
|> reduce(0, ({nx, ny}, acc) -> (state[x + nx][y + ny] || 0) + acc)
alive(1, n) -> if n in 2..3, do: 1, else: 0
alive(0, n) -> if n == 3, do: 1, else: 0
step(state) ->
[{x, y, val} || {x, row} <- state, {y, val} <- row]
|> reduce(state, {x, y, val}, acc -> put_in acc, [key(x), key(y)], (neighbours(x,y, state) |> alive(val)))
defmodule GameOfLife do
import Enum
import Access
def neighbours(x,y, state) do
(for nx <- -1..1, ny <- -1..1, do: {nx, ny})
|> reduce(0, fn {nx, ny}, acc -> (state[x + nx][y + ny] || 0) + acc end)
end
def alive(1, n), do a: if n in 2..3, do: 1, else: 0
def alive(0, n), do: if n == 3, do: 1, else: 0
def step(state) do
(for {x, row} <- state, {y, val} <- row, do: {x,y,val})
|> reduce(state, fn {x, y, val}, acc -> put_in acc, [key(x), key(y)], (neighbours(x,y, state) |> alive(val)) end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment