52 lines
1.4 KiB
Haskell
52 lines
1.4 KiB
Haskell
module Day10 where
|
|
|
|
import Data.Maybe
|
|
import Text.Blaze.Html4.FrameSet (input)
|
|
import Data.List (sort)
|
|
closing :: Char -> Char
|
|
closing '(' = ')'
|
|
closing '[' = ']'
|
|
closing '{' = '}'
|
|
closing '<' = '>'
|
|
|
|
score :: Char -> Int
|
|
score ' ' = 0
|
|
score ')' = 3
|
|
score ']' = 57
|
|
score '}' = 1197
|
|
score '>' = 25137
|
|
|
|
closingScore :: Char -> Int
|
|
closingScore ')' = 1
|
|
closingScore ']' = 2
|
|
closingScore '}' = 3
|
|
closingScore '>' = 4
|
|
|
|
calcScore :: String -> Int
|
|
calcScore xs = foldr (\char score -> score*5 + closingScore char) 0 (reverse xs)
|
|
|
|
|
|
getInvalidChar :: [Char] -> String -> Char
|
|
getInvalidChar _ [] = ' '
|
|
getInvalidChar st (x:xs)
|
|
| x == '(' || x == '[' || x == '{' || x == '<' = getInvalidChar (x:st) xs
|
|
| otherwise = if Just x == fmap closing (listToMaybe st) then getInvalidChar (tail st) xs else x
|
|
|
|
getCompletionString :: [Char] -> String -> String
|
|
getCompletionString st [] = map closing st
|
|
getCompletionString st (x:xs)
|
|
| x == '(' || x == '[' || x == '{' || x == '<' = getCompletionString (x:st) xs
|
|
| otherwise = if Just x == fmap closing (listToMaybe st) then getCompletionString (tail st) xs else ""
|
|
|
|
|
|
main :: IO ()
|
|
main = do
|
|
input <- lines <$> getContents
|
|
|
|
putStr "part 1: "
|
|
let chars = map (score . getInvalidChar []) input
|
|
print $ sum chars
|
|
|
|
putStr "part 2: "
|
|
let compls = filter (> 0) $ map (calcScore . getCompletionString []) input
|
|
print $ sort compls !! (length compls `div` 2) |