fcc28d367e243f2911e82f17e631dc7a5a47faca
[advent-of-code-17.git] / src / advent21 / advent21.hs
1 {-# LANGUAGE NegativeLiterals #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE OverloadedStrings #-}
4 {-# LANGUAGE TypeFamilies #-}
5 {-# LANGUAGE BangPatterns #-}
6
7 import Data.Text (Text)
8 import qualified Data.Text as T
9 import qualified Data.Text.IO as TIO
10
11 import Text.Megaparsec hiding (State)
12 import qualified Text.Megaparsec.Lexer as L
13 import Text.Megaparsec.Text (Parser)
14 import qualified Control.Applicative as CA
15
16 import qualified Data.Map.Strict as M
17
18 import Data.List
19
20
21 type Grid = M.Map (Int, Int) Bool
22 type ExplodedGrid = M.Map (Int, Int) Grid
23
24 data Rule = Rule Grid Grid deriving (Eq, Show)
25
26 rulePre (Rule g _) = g
27 rulePost (Rule _ g) = g
28
29
30 initialGrid = case parse gridP "" ".#./..#/###" of
31 Left _ -> M.empty
32 Right g -> g
33
34
35 main :: IO ()
36 main = do
37 text <- TIO.readFile "data/advent21.txt"
38 let rules = readRules text
39 print $ countLit $ nthApplication rules 5
40 print $ countLit $ nthApplication rules 18
41
42
43 -- Read the rules, and expand them to all equivalent left hand sides
44 readRules :: Text -> [Rule]
45 readRules = expandRules . successfulParse
46
47
48 expandRules :: [Rule] -> [Rule]
49 expandRules = concatMap expandRule
50
51 expandRule :: Rule -> [Rule]
52 expandRule rule = [Rule l (rulePost rule) | l <- allArrangements (rulePre rule)]
53
54
55 reflectH :: Grid -> Grid
56 reflectH g = M.fromList [((r, c) , M.findWithDefault False (rm - r, c) g) | r <- [0..rm], c <- [0..cm] ]
57 where (rm, cm) = bounds g
58
59 reflectV :: Grid -> Grid
60 reflectV g = M.fromList [((r, c) , M.findWithDefault False (r, cm - c) g) | r <- [0..rm], c <- [0..cm] ]
61 where (rm, cm) = bounds g
62
63 -- awkward naming to avoid clashing with Prelude
64 transposeG :: Grid -> Grid
65 transposeG g = M.fromList [((c, r) , M.findWithDefault False (r, c) g) | r <- [0..rm], c <- [0..cm] ]
66 where (rm, cm) = bounds g
67
68
69 -- Find all the arrangments of a grid, including reflection and rotation.
70 allArrangements :: Grid -> [Grid]
71 allArrangements grid = map (\f -> f grid) [ id
72 , reflectH
73 , reflectV
74 , transposeG
75 , reflectH . transposeG
76 , reflectV . transposeG
77 , reflectH . reflectV . transposeG
78 , reflectV . reflectH
79 ]
80
81
82
83 -- Count number of lit pixels
84 countLit :: Grid -> Int
85 countLit = M.size . M.filter id
86
87 -- apply the rules _n_ times
88 nthApplication :: [Rule] -> Int -> Grid
89 nthApplication rules n = (!! n) $ iterate (applyOnce rules) initialGrid
90
91 -- Apply one step of the expansion
92 applyOnce :: [Rule] -> Grid -> Grid
93 applyOnce rules g = contractExploded $ M.map (apply rules) $ explodeGrid g
94
95 -- find the appropriate rule and apply it to a grid
96 apply :: [Rule] -> Grid -> Grid
97 apply rules grid = rulePost thisRule
98 where ri = head $ findIndices (\r -> rulePre r == grid) rules
99 thisRule = rules!!ri
100
101
102 -- create the appropriate subgrids of a grid
103 explodeGrid :: Grid -> ExplodedGrid
104 explodeGrid g = if (rm + 1) `rem` 2 == 0
105 then explodeGrid' 2 g
106 else explodeGrid' 3 g
107 where (rm, _cm) = bounds g
108
109 explodeGrid' :: Int -> Grid -> ExplodedGrid
110 explodeGrid' n g = M.fromList [((bigR, bigC), subGrid n g bigR bigC) | bigR <- [0..bigRm], bigC <- [0..bigCm]]
111 where (rm, cm) = bounds g
112 bigRm = (rm + 1) `div` n - 1
113 bigCm = (cm + 1) `div` n - 1
114
115
116 subGrid :: Int -> Grid -> Int -> Int -> Grid
117 subGrid n g bigR bigC = M.fromList [ ((r, c),
118 M.findWithDefault False (r + rStep, c + cStep) g)
119 | r <- [0..(n - 1)], c <- [0..(n - 1)]
120 ]
121 where rStep = bigR * n
122 cStep = bigC * n
123
124 -- merge a set of subgrids into one
125 contractExploded :: ExplodedGrid -> Grid
126 contractExploded gs = foldl1 (>|<) $ map (foldl1 (>-<)) rows
127 where rows = explodedRows gs
128
129 -- find the rows of an exploded grid
130 explodedRows :: ExplodedGrid -> [ExplodedGrid]
131 explodedRows eg = [M.filterWithKey (\(r, _) _ -> r == row) eg | row <- [0..rowMax] ]
132 where (rowMax, _) = bounds eg
133
134 -- merge two grids horizontally
135 (>-<) :: Grid -> Grid -> Grid
136 (>-<) g1 g2 = M.union g1 g2'
137 where (_, cm) = bounds g1
138 g2' = M.mapKeys (\(r, c) -> (r, c + cm + 1)) g2
139
140 -- merge two grids vertically
141 (>|<) :: Grid -> Grid -> Grid
142 (>|<) g1 g2 = M.union g1 g2'
143 where (rm, _) = bounds g1
144 g2' = M.mapKeys (\(r, c) -> (r + rm + 1, c)) g2
145
146
147
148
149 bounds :: M.Map (Int, Int) a -> (Int, Int)
150 bounds grid = (maximum $ map fst $ M.keys grid, maximum $ map snd $ M.keys grid)
151
152
153 showGrid :: Grid -> String
154 showGrid g = unlines [[showGChar $ M.findWithDefault False (r, c) g |
155 c <- [0..cm] ] | r <- [0..rm] ]
156 where (rm, cm) = bounds g
157 showGChar True = '#'
158 showGChar False = '.'
159
160
161
162 -- really persuade Megaparsec not to include newlines in how it consume spaces.
163 onlySpace = (char ' ') <|> (char '\t')
164
165 sc :: Parser ()
166 sc = L.space (skipSome onlySpace) CA.empty CA.empty
167
168 symbol = L.symbol sc
169 rowSep = symbol "/"
170 ruleJoin = symbol "=>"
171
172 present = id True <$ symbol "#"
173 absent = id False <$ symbol "."
174
175 rulesP = ruleP `sepBy` space
176 ruleP = Rule <$> gridP <* ruleJoin <*> gridP
177
178 gridP = gridify <$> rowP `sepBy` rowSep
179 where gridify g = M.fromList $ concat
180 [map (\(c, v) -> ((r, c), v)) nr |
181 (r, nr) <- zip [0..]
182 [zip [0..] r | r <- g]]
183
184
185 rowP = some (present <|> absent)
186
187 successfulParse :: Text -> [Rule]
188 successfulParse input =
189 case parse rulesP "input" input of
190 Left _error -> []
191 Right instructions -> instructions