Skip to content

Instantly share code, notes, and snippets.

@yuanmai
Last active April 29, 2016 08:35
Show Gist options
  • Save yuanmai/0e19e6639c2ec81ac8a7 to your computer and use it in GitHub Desktop.
Save yuanmai/0e19e6639c2ec81ac8a7 to your computer and use it in GitHub Desktop.
(defn neighbours [cell]
(map (partial mapv + cell)
[[-1 -1] [-1 0] [-1 1]
[ 0 -1] [ 0 1]
[ 1 -1] [ 1 0] [ 1 1]]))
(def live? #{[true 3] [true 2] [false 3]})
(defn step [live-cells]
(set
(for [[cell live-neighbours]
(frequencies (mapcat neighbours live-cells))
:when (live? [(contains? live-cells cell) live-neighbours])]
cell)))
(def blinker #{[1 0] [1 1] [1 2]})
(take 5 (iterate step blinker))
let live = Set.ofList [(true, 2); (true, 3); (false, 3)]
let neighbours (x,y) = [
(x-1,y-1); (x-1,y); (x-1,y+1);
(x ,y-1); (x ,y+1);
(x+1,y-1); (x+1,y); (x+1,y+1)]
let freq xs =
xs
|> Seq.groupBy Operators.id
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
let willLive liveCells (cell, numberOfNei) =
let isLivingCell = (Set.contains cell liveCells)
Set.contains (isLivingCell, numberOfNei) live
let step liveCells =
liveCells
|> Seq.map neighbours
|> Seq.concat
|> freq
|> Seq.filter (willLive liveCells)
|> Seq.map (fun (x,_) -> x)
|> Set.ofSeq
step (step (Set.ofList [(1,0); (1,1); (1,2)]))
from collections import Counter
def neighbours(cell):
(x,y) = cell
return [(x+dx, y+dy) for dx,dy in [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]]
live = [(True,2), (True,3), (False,3)]
def step(live_cells):
counter = Counter(reduce(list.__add__, [neighbours(cell) for cell in live_cells]))
return [cell for cell in counter if (cell in live_cells, counter[cell]) in live]
blinker = [(1,0), (1,1), (1,2)]
print step(step(step(blinker)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment