-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-10.hs
executable file
·53 lines (43 loc) · 1.38 KB
/
day-10.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env stack
-- stack --resolver=lts-18.18 script --package split --package containers --package array
import Data.List
import Control.Monad
import Data.Either
main :: IO ()
main = do
input <- fmap lines getContents
putStrLn $ show $ scoreErrors input
putStrLn $ show $ scoreChunks input
type ParseResult = Either Int
parseChunks :: String -> ParseResult [Char]
parseChunks = foldM pushBracket []
pushBracket :: [Char] -> Char -> ParseResult [Char]
pushBracket ('(':s) ')' = Right s
pushBracket ('[':s) ']' = Right s
pushBracket ('{':s) '}' = Right s
pushBracket ('<':s) '>' = Right s
pushBracket s '(' = Right $ '(':s
pushBracket s '[' = Right $ '[':s
pushBracket s '{' = Right $ '{':s
pushBracket s '<' = Right $ '<':s
pushBracket _ c = Left $ errorScore c
errorScore :: Char -> Int
errorScore ')' = 3
errorScore ']' = 57
errorScore '}' = 1197
errorScore '>' = 25137
scoreErrors :: [String] -> Int
scoreErrors = sum . lefts . (map parseChunks)
scoreChunk :: [Char] -> Int
scoreChunk s = foldl addBracketScore 0 s
where addBracketScore score c = score * 5 + completionScore c
completionScore :: Char -> Int
completionScore '(' = 1
completionScore '[' = 2
completionScore '{' = 3
completionScore '<' = 4
scoreChunks :: [String] -> Int
scoreChunks ss = scores !! mid
where
scores = sort $ map scoreChunk $ rights $ map parseChunks ss
mid = floor $ (fromIntegral $ length scores) / 2