Skip to content

Instantly share code, notes, and snippets.

@hardentoo
Forked from sordina/Life.hs
Created March 12, 2018 01:18
Show Gist options
  • Save hardentoo/19bdaebef4f1e0de81f3cc7d6bc116a1 to your computer and use it in GitHub Desktop.
Save hardentoo/19bdaebef4f1e0de81f3cc7d6bc116a1 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 -- There is no 'off-by-one' error here
| n > 4 = 0 -- I'm including the center cell in the total
| 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 -- Window function
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