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