Skip to content

Instantly share code, notes, and snippets.

@veeenu
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veeenu/8dbba3e53f94d7142c63 to your computer and use it in GitHub Desktop.
Save veeenu/8dbba3e53f94d7142c63 to your computer and use it in GitHub Desktop.
Haskell cellular automaton
import System.Random
getCell :: Int -> Int -> [Int] -> Int
getCell x y vec = head $ drop ((clamp y) * 32 + (clamp x)) vec
where clamp i = min 31 (max 0 i)
generation :: Int -> [Int] -> [Int]
generation 0 vec = vec
generation i vec = map step [0 .. length vec]
where
vec' = generation (i-1) vec
step :: Int -> Int
step i = if (neighSum > 4) then 1 else 0
where
x = i `mod` 32
y = i `div` 32
neighSum = foldr (+) 0 [getCell (x + x') (y + y') vec' | x' <- [-1..1], y' <- [-1..1], not (x' == 0 && y' == 0) ]
render :: [Int] -> [Char]
render [] = []
render vec = (renderLine $ take 32 vec) ++ ['\n'] ++ (render $ drop 32 vec)
where
renderLine :: [Int] -> [Char]
renderLine (x:xs)
| x == 0 = [' ', ' '] ++ renderLine xs
| x == 1 = ['*', ' '] ++ renderLine xs
renderLine [] = []
main = do
g <- getStdGen
let gen0 = (take 1024 (randomRs (0 :: Int, 1 :: Int) g))
putStr . render $ generation 0 gen0
putStrLn ['\n', '\n', '\n']
putStr . render $ generation 1 gen0
putStrLn ['\n', '\n', '\n']
putStr . render $ generation 2 gen0
putStrLn ['\n', '\n', '\n']
putStr . render $ generation 3 gen0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment