Skip to content

Instantly share code, notes, and snippets.

Created December 5, 2011 07:17
Show Gist options
  • Save anonymous/1432673 to your computer and use it in GitHub Desktop.
Save anonymous/1432673 to your computer and use it in GitHub Desktop.
Small game of life implementation
import Data.List
import Control.Arrow
import System.Random
-- Core Life Engine
life = f 3 >>> map (map (q 3 >>> uncurry s))
s n 1 | n < 3 = 0
| n > 4 = 0
| otherwise = 1
s n 0 | n == 3 = 1
| otherwise = 0
s _ _ = 1 -- Shouldn't be needed, but using this for thinning out the matrix
f n = map (g n) . m n
where
g n = map concat . m n . transpose
m n = takeWhile ((==n) . length) . map (take n) . tails
q n = sum &&& (!!(n^2 `div` 2))
-- IO
main = dolife 80
dolife n = fmap (take n . splitLen n . randomRs (0, 5::Int)) getStdGen
>>= mapM_ (putStrLn . unlines . map string) . iterate (life . e n)
splitLen n l = take n l : splitLen n (drop n l)
e n = x . map x where x = take (n + 2) . drop (n - 1) . cycle -- Loop World
string = map (\x -> if x == 1 then 'X' else ' ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment