1 -- Writeup at https://work.njae.me.uk/2021/12/16/advent-of-code-2021-day-15/
5 -- import qualified Data.Text.IO as TIO
7 import qualified Data.PQueue.Prio.Min as P
8 import qualified Data.Set as S
9 import qualified Data.Sequence as Q
10 import Data.Sequence ((<|), (|>), (><)) --, ViewR( (:>) ), ViewL( (:<) ))
11 import Data.Foldable (foldl', sum) -- (toList, foldr', foldl', all)
13 import Control.Monad.Reader
14 import Control.Lens hiding ((<|), (|>), (:>), (:<))
15 -- import Data.Maybe (fromMaybe)
16 import Linear (V2(..), (^+^), (^-^), (*^), (^*))
17 import Data.Array.IArray
19 pattern Empty <- (Q.viewl -> Q.EmptyL) where Empty = Q.empty
20 pattern x :< xs <- (Q.viewl -> x Q.:< xs) where (:<) = (Q.<|)
21 pattern xs :> x <- (Q.viewr -> xs Q.:> x) where (:>) = (Q.|>)
23 type BasePosition = V2 Int -- r, c
24 newtype Position = Position BasePosition -- r, c
25 deriving (Eq, Ord, Show)
26 newtype TiledPosition = TiledPosition BasePosition -- r, c
27 deriving (Eq, Ord, Show)
28 type Grid = Array BasePosition Int
32 , _goal :: BasePosition
33 } deriving (Eq, Ord, Show)
36 type CaveContext = Reader Cave
39 Agendum { _current :: s
46 type Agenda s = P.MinPQueue Int (Agendum s)
48 type ExploredStates s = S.Set s
50 class (Eq s, Ord s, Show s) => SearchState s where
51 unwrapPos :: s -> BasePosition
53 successors :: s -> CaveContext (Q.Seq s)
54 estimateCost :: s -> CaveContext Int
55 isGoal :: s -> CaveContext Bool
56 entryCost :: s -> CaveContext Int
59 instance SearchState Position where
61 unwrapPos (Position p) = p
63 emptySearchState = Position (V2 0 0)
65 -- successors :: Position -> CaveContext (Q.Seq Position)
66 successors (Position here) =
69 filter (inRange (bounds grid))
71 | delta <- [V2 -1 0, V2 1 0, V2 0 -1, V2 0 1]
73 let succs = Q.fromList $ map Position neighbours
76 -- estimateCost :: Position -> CaveContext Int
77 estimateCost (Position here) =
79 let (V2 dr dc) = here ^-^ goal
80 return $ (abs dr) + (abs dc)
82 -- isGoal :: here -> CaveContext Bool
83 isGoal (Position here) =
87 entryCost (Position here) =
91 instance SearchState TiledPosition where
93 unwrapPos (TiledPosition p) = p
95 emptySearchState = TiledPosition (V2 0 0)
97 -- successors :: Position -> CaveContext (Q.Seq Position)
98 successors (TiledPosition here) =
100 let (lowBound, highBound) = bounds grid
101 let extendedBounds = ( lowBound
102 , tileScale highBound
105 filter (inRange extendedBounds)
107 | delta <- [V2 -1 0, V2 1 0, V2 0 -1, V2 0 1]
109 let succs = Q.fromList $ map TiledPosition neighbours
112 -- estimateCost :: Position -> CaveContext Int
113 estimateCost (TiledPosition here) =
114 do goal <- asks _goal
115 let (V2 dr dc) = here ^-^ (tileScale goal)
116 return $ (abs dr) + (abs dc)
118 -- isGoal :: here -> CaveContext Bool
119 isGoal (TiledPosition here) =
120 do goal <- asks _goal
121 return $ here == (tileScale goal)
123 entryCost (TiledPosition (V2 r c)) =
124 do grid <- asks _grid
125 let (_, V2 maxR maxC) = bounds grid
126 let (tileR, gridR) = r `divMod` (maxR + 1)
127 let (tileC, gridC) = c `divMod` (maxC + 1)
128 let gridCost = grid ! (V2 gridR gridC)
129 let !cost = (gridCost - 1 + tileR + tileC) `mod` 9 + 1
132 tileScale :: BasePosition -> BasePosition
133 tileScale (V2 r c) = V2 (ts r) (ts c)
134 where ts n = (n + 1) * 5 - 1
136 ------------------------------
140 do text <- readFile "data/advent15.txt"
141 let cave = mkCave text
144 -- print $ part2 grid
146 mkCave :: String -> Cave
147 mkCave text = Cave { _grid = grid, _goal = V2 r c }
148 where rows = lines text
150 c = (length $ head rows) - 1
151 grid = listArray ((V2 0 0), (V2 r c)) $ map mkCell $ concat rows
152 mkCell e = digitToInt e
156 part1 cave = maybe 0 _cost result
157 where result = runReader searchCave cave :: Maybe (Agendum Position)
160 part2 cave = maybe 0 _cost result
161 where result = runReader searchCave cave :: Maybe (Agendum TiledPosition)
164 searchCave :: SearchState s => CaveContext (Maybe (Agendum s))
166 do agenda <- initAgenda
169 initAgenda :: SearchState s => CaveContext (Agenda s)
171 do let ss = emptySearchState
173 return $ P.singleton c Agendum { _current = ss, _trail = Q.empty, _trailCost = 0, _cost = c}
176 aStar :: SearchState s => Agenda s -> ExploredStates s -> CaveContext (Maybe (Agendum s))
178 -- | trace ("Peeping " ++ (show $ fst $ P.findMin agenda) ++ ": " ++ (show reached) ++ " <- " ++ (show $ toList $ Q.take 1 $ _trail $ currentAgendum) ++ " :: " ++ (show newAgenda)) False = undefined
179 -- | trace ("Peeping " ++ (show $ _current $ snd $ P.findMin agenda) ) False = undefined
180 | P.null agenda = return Nothing
182 do let (_, currentAgendum) = P.findMin agenda
183 let reached = currentAgendum ^. current
184 nexts <- candidates currentAgendum closed
185 let newAgenda = foldl' (\q a -> P.insert (_cost a) a q) (P.deleteMin agenda) nexts
186 reachedGoal <- isGoal reached
188 then return (Just currentAgendum)
189 else if reached `S.member` closed
190 then aStar (P.deleteMin agenda) closed
191 else aStar newAgenda (S.insert reached closed)
194 candidates :: SearchState s => Agendum s -> ExploredStates s -> CaveContext (Q.Seq (Agendum s))
195 candidates agendum closed =
196 do let candidate = agendum ^. current
197 let previous = agendum ^. trail
198 let prevCost = agendum ^. trailCost
199 succs <- successors candidate
200 let nonloops = Q.filter (\s -> s `S.notMember` closed) succs
201 mapM (makeAgendum previous prevCost) nonloops
204 makeAgendum :: SearchState s => (Q.Seq s) -> Int -> s -> CaveContext (Agendum s)
205 makeAgendum previous prevCost newPosition =
206 do predicted <- estimateCost newPosition
208 let newTrail = previous |> newPosition
209 newPositionCost <- entryCost newPosition
210 let incurred = prevCost + newPositionCost
211 return Agendum { _current = newPosition
213 , _trailCost = incurred
214 , _cost = incurred + predicted