Tidying
[advent-of-code-18.git] / src / advent05 / advent05.hs
1 import Data.List
2 import Data.Char (toLower)
3
4 main :: IO ()
5 main = do
6 text <- readFile "data/advent05.txt"
7 print $ part1 text
8 print $ part2 text
9
10 part1 = reactedLength
11
12 part2 polymer = minimum finalLengths
13 where finalLengths = map (\u -> reactedLength $ removeUnit polymer u) units
14 units = unitsPresent polymer
15
16
17 react :: String -> Char -> Char -> String -> (String, String)
18 react prefix a b suffix =
19 if willReact a b
20 then (prefix, suffix)
21 else ((b:a:prefix), suffix)
22
23 willReact :: Char -> Char -> Bool
24 willReact a b = (a /= b) && (toLower a == toLower b)
25
26
27 reactHere :: (String, String) -> Maybe ((String, String), (String, String))
28 reactHere (prefix, suffix) =
29 if canContinue prefix suffix
30 then Just ((prefix'', suffix''), (prefix'', suffix''))
31 else Nothing
32 where (prefix', a, b, suffix') = reactionSite prefix suffix
33 (prefix'', suffix'') = react prefix' a b suffix'
34
35
36 canContinue (_:_) (_:_) = True
37 canContinue [] (_:_:_) = True
38 canContinue _ _ = False
39
40 reactionSite (a:prefix) (b:suffix) = (prefix, a, b, suffix)
41 reactionSite [] (a:b:suffix) = ([], a, b, suffix)
42
43
44 reactedLength polymer = length prefix + length suffix
45 where (prefix, suffix) = last $ unfoldr reactHere ("", polymer)
46
47
48 unitsPresent = nub . sort . map toLower
49
50 removeUnit polymer unit = filter (\c -> toLower c /= unit ) polymer