Skip to content

Instantly share code, notes, and snippets.

@arnihermann
Created January 7, 2013 01:40
Show Gist options
  • Save arnihermann/4471624 to your computer and use it in GitHub Desktop.
Save arnihermann/4471624 to your computer and use it in GitHub Desktop.
runhaskell gameoflife.hs
import Control.Monad (forM_)
import Data.Function (on)
import Data.List (group,intercalate,maximumBy,nub,sort)
import Data.List.Split (chunksOf)
-- see http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/
neighbours [x, y] = [[dx + x, dy + y] | dx <- [-1,0,1]
, dy <- if (dx == 0) then [-1,1] else [-1,0,1]]
step cells = nub $ [loc | (loc, n) <- frequencies $ concatMap neighbours cells, cond loc n]
where frequencies input = map (\x -> (head x, length x)) $ group $ sort input
cond loc n = n == 3 || (n == 2 && loc `elem` cells)
fullBoard cells = chunksOf (size + 1) [[y,x] `elem` cells | x <- [0..size], y <- [0..size]]
where n = maximum $ map head cells
m = maximum $ map (head.tail) cells
size = max n m
printableBoard cells = intercalate "\n" (map (intercalate " ") xo)
where xo = map (\row -> map (\item -> if item then "O" else "X") row) $ fullBoard cells
main = do
let board = [[1,0], [1,1], [1,2]]
boards = take 5 $ iterate step board
forM_ boards $ \b -> do
putStrLn $ printableBoard b
putStrLn ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment