### Solution for 5

Abhinav Sarkar 2 years ago
parent
commit
3db4dc2e9b
1 changed files with 44 additions and 0 deletions
1. 44
0
5/5.hs

#### + 44 - 0 5/5.hsView File

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