Solutions for adventofcode.com/2018
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5.hs 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. module Main where
  2. import Data.Char
  3. import Data.Foldable (toList)
  4. import Data.Function (on)
  5. import Data.List (minimumBy)
  6. import qualified Data.Sequence as S
  7. import Data.Sequence ((><), (|>))
  8. xor :: Bool -> Bool -> Bool
  9. xor True False = True
  10. xor False True = True
  11. xor _ _ = False
  12. isReactive :: Char -> Char -> Bool
  13. isReactive x y = toLower x == toLower y && (isUpper x `xor` isUpper y)
  14. simplify :: S.Seq Char -> S.Seq Char -> S.Seq Char
  15. simplify acc s
  16. | S.null s = acc
  17. | S.length s == 1 = acc >< s
  18. | S.length s >= 2 =
  19. let [x,y] = toList (S.take 2 s)
  20. in if isReactive x y
  21. then simplify acc (S.drop 2 s)
  22. else simplify (acc |> x) (S.drop 1 s)
  23. collapse :: S.Seq Char -> S.Seq Char
  24. collapse s =
  25. let simplified = simplify S.empty s
  26. in if S.length simplified == S.length s
  27. then s
  28. else collapse simplified
  29. betterCollapse :: S.Seq Char -> S.Seq Char
  30. betterCollapse s =
  31. minimumBy (compare `on` S.length)
  32. . map (\c -> collapse $ S.filter (\c' -> toLower c' /= toLower c) s)
  33. $ ['a' .. 'z']
  34. main = do
  35. input <- S.fromList . filter (/= '\n') <$> getContents
  36. putStrLn $ "Size = " ++ show (S.length $ collapse input)
  37. putStrLn $ "Better Size = " ++ show (S.length $ betterCollapse (collapse input))