Day 9
[advent-of-code-17.git] / src / advent09 / advent09.hs
1 data ParseState = ParseState
2 { total :: Int
3 , depth :: Int
4 , garbageCount :: Int
5 , readingGarbage :: Bool
6 , ignoreCharacter :: Bool
7 } deriving (Show, Eq)
8
9 main :: IO ()
10 main = do
11 text <- readFile "data/advent09.txt"
12 print $ part1 text
13 print $ part2 text
14
15
16 part1 :: String -> Int
17 part1 = total . process
18
19 part2 :: String -> Int
20 part2 = garbageCount . process
21
22
23 process :: String -> ParseState
24 process = foldl parse ps0
25 where ps0 = ParseState {total = 0, depth = 0, garbageCount = 0,
26 readingGarbage = False, ignoreCharacter = False}
27
28 parse :: ParseState -> Char -> ParseState
29 parse ps c
30 | ignoreCharacter ps = ps {ignoreCharacter = False}
31 | c == '!' = ps {ignoreCharacter = True}
32 | readingGarbage ps = if c == '>'
33 then ps {readingGarbage = False}
34 else ps {garbageCount = garbageCount ps + 1}
35 | otherwise =
36 case c of
37 '<' -> ps {readingGarbage = True}
38 '{' -> openGroup ps
39 '}' -> closeGroup ps
40 _ -> ps
41
42 openGroup :: ParseState -> ParseState
43 openGroup ps = ps {depth = depth ps + 1}
44
45 closeGroup :: ParseState -> ParseState
46 closeGroup ps = ps {total = total ps + depth ps, depth = depth ps - 1}