this repo has no description
1module Lib
2 ( imgStart
3 , parseRules
4 , stepProgram
5 , countOnPixels
6 ) where
7
8import Data.List.Split (splitOn)
9import Data.List (find, foldl')
10
11imgStart :: [String]
12imgStart = [ ".#."
13 , "..#"
14 , "###"
15 ]
16
17stepProgram :: [([String], [String])] -> [String] -> [String]
18stepProgram rules program =
19 let x = if (mod (length program) 2 == 0) then 2 else 3
20 sections = sectionUp x program
21 in recombine $ map (map $ findRule rules) $ sections
22
23countOnPixels :: [String] -> Int
24countOnPixels = length . filter (== '#') . concat
25
26sectionUp :: Int -> [String] -> [[[String]]]
27sectionUp x l = map (\sec ->
28 map (\s ->
29 map (\l' -> take x . snd . splitAt s $ l') sec
30 ) $ init [0,x..(length l)]
31 ) sections
32 where sections = map (\s -> (take x . snd . splitAt s) l) $ init [0,x..(length l)]
33
34recombine :: [[[String]]] -> [String]
35recombine [] = []
36recombine (x:xs) =
37 let combinedSection = map (\i -> foldl' (\acc s -> acc ++ (s !! i)) "" x) [0..length (head x) - 1]
38 in combinedSection ++ recombine xs
39
40parseRules :: [String] -> [([String], [String])]
41parseRules [] = []
42parseRules (r:rs) = let match = splitOn "/" . head . splitOn " => " $ r
43 rule = splitOn "/" . last . splitOn " => " $ r
44 in (match, rule) : parseRules rs
45
46findRule :: [([String], [String])] -> [String] -> [String]
47findRule rules section =
48 case find (\(m, _) -> m `elem` sectionPermutations section) rules of
49 Just (_, r) -> r
50 Nothing -> []
51
52sectionPermutations :: [String] -> [[String]]
53sectionPermutations str =
54 (take 4 . iterate rotateSection $ str) ++ (take 4 . iterate rotateSection $ flipSection str)
55
56rotateSection :: [String] -> [String]
57rotateSection (x:y:[]) = [(y!!0:x!!0:""), (y!!1:x!!1:"")]
58rotateSection (x:y:z:[]) =
59 [(z!!0:y!!0:x!!0:""), (z!!1:y!!1:x!!1:""), (z!!2:y!!2:x!!2:"")]
60rotateSection _ = []
61
62flipSection :: [String] -> [String]
63flipSection (x:y:[]) = [(x!!1:x!!0:""), (y!!1:y!!0:"")]
64flipSection (x:y:z:[]) = [(x!!2:x!!1:x!!0:""), (y!!2:y!!1:y!!0:""), (z!!2:z!!1:z!!0:"")]
65flipSection _ = []