-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay08.hs
114 lines (91 loc) · 2.72 KB
/
Day08.hs
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE RecordWildCards #-}
module Day08 where
import Control.Monad
import Data.Char
import Data.Map (Map)
import Text.ParserCombinators.ReadP
import Harness
import ParseHelper
import Data.Map qualified as M
-- (parseInput lineParser) OR (parseInputRaw fullInputParser)
main :: IO ()
main = getInputAndSolve (parseInputRaw parseNetwork) stepsTilZZZs spookyTime
-- SOLVE
stepsTilZZZs :: Network -> Int
stepsTilZZZs network =
either id (error . ("Unexpected: " <>) . show) $
foldM
(followLinks network.links (== "ZZZ"))
("AAA", 0)
(cycle network.steps)
spookyTime :: Network -> Int
spookyTime network =
let nodesThatEndInA = filter endsInA $ M.keys network.links
getStepToEndInZ node =
either id (error . ("Unexpected: " <>) . show) $
foldM
(followLinks network.links endsInZ)
(node, 0)
(cycle network.steps)
stepsToZ = map getStepToEndInZ nodesThatEndInA
in foldr lcm 1 stepsToZ
where
endsInA :: String -> Bool
endsInA = \case
[_, _, 'A'] -> True
_ -> False
endsInZ :: String -> Bool
endsInZ = \case
[_, _, 'Z'] -> True
_ -> False
-- HELPERS
followLinks
:: Map String (String, String)
-> (String -> Bool)
-> (String, Int)
-> Direction
-> Either Int (String, Int)
followLinks linkMap isEnd (currentLocation, stepCount) nextDirection =
if isEnd currentLocation
then Left stepCount
else case M.lookup currentLocation linkMap of
Nothing ->
error $ "Loc not found: " <> currentLocation
Just (l, r) ->
if nextDirection == RightD then Right (r, succ stepCount) else Right (l, succ stepCount)
-- PARSE
data Network = Network
{ steps :: [Direction]
, links :: M.Map String (String, String)
}
deriving (Show)
parseNetwork :: ReadP Network
parseNetwork = do
!steps <- many1 parseDirection <* newline <* newline
links <- M.fromList <$> endBy1 parseLink newline
eof
return Network {..}
where
parseLink :: ReadP (String, (String, String))
parseLink = do
key <- many1 (satisfy isAlphaNum)
void $ string " = ("
left <- many1 (satisfy isAlphaNum)
void $ string ", "
right <- many1 (satisfy isAlphaNum)
void $ string ")"
return (key, (left, right))
data Direction
= RightD
| LeftD
deriving (Show, Eq)
parseDirection :: ReadP Direction
parseDirection =
choice
[ RightD <$ char 'R'
, LeftD <$ char 'L'
]