2 import Data.Char (toLower)
6 text <- readFile "data/advent05.txt"
12 part2 polymer = minimum finalLengths
13 where finalLengths = map (\u -> reactedLength $ removeUnit polymer u) units
14 units = unitsPresent polymer
17 react :: String -> Char -> Char -> String -> (String, String)
18 react prefix a b suffix =
21 else ((b:a:prefix), suffix)
23 willReact :: Char -> Char -> Bool
24 willReact a b = (a /= b) && (toLower a == toLower b)
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''))
32 where (prefix', a, b, suffix') = reactionSite prefix suffix
33 (prefix'', suffix'') = react prefix' a b suffix'
36 canContinue (_:_) (_:_) = True
37 canContinue [] (_:_:_) = True
38 canContinue _ _ = False
40 reactionSite (a:prefix) (b:suffix) = (prefix, a, b, suffix)
41 reactionSite [] (a:b:suffix) = ([], a, b, suffix)
44 reactedLength polymer = length prefix + length suffix
45 where (prefix, suffix) = last $ unfoldr reactHere ("", polymer)
48 unitsPresent = nub . sort . map toLower
50 removeUnit polymer unit = filter (\c -> toLower c /= unit ) polymer