1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
module Main where
import System.Environment
import Control.Monad
import System.Random (newStdGen, randomRs)
import Data.List.Split
main :: IO ()
main = do
args <- getArgs
case args of
[] -> putStrLn "Needs one argument"
(n:_) -> run (read n :: Int)
-- | Run the cellular automata with a random seed.
run :: Int -> IO ()
run n = do
g <- newStdGen
let init = take n $ randomRs (0,1) g
run' init
-- | Version of 'run' that allows for entering your own initial seed.
run' :: [Int] -> IO ()
run' init = do
let n = length init
let zeros = take n $ repeat 0
let result = takeWhile' (/= zeros) $ chunksOf n $ compute n init
forM_ result $ \r -> putStrLn $ show r
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' _ [] = []
takeWhile' p (x:xs) = x : if p x then takeWhile' p xs else []
compute :: Int -> [Int] -> [Int]
compute n state = state ++ compute n (next n state)
next :: Int -> [Int] -> [Int]
next n state = [left, center, right]
where
center = translate $ getLast n' state
right = translate $ getLast (n'+1) state
left = translate $ getLast (n'-1) state
n' = n+n
getLast :: Int -> [a] -> [a]
getLast n ls = drop (length ls - n) ls
translate [0,0,0] = 0
translate [0,0,1] = 1
translate [0,1,0] = 1
translate [0,1,1] = 1
translate [1,0,0] = 0
translate [1,0,1] = 1
translate [1,1,0] = 1
translate [1,1,1] = 0
translate _ = 0
|