summaryrefslogtreecommitdiff
path: root/2021/10.hs
blob: ab90d8868363060583d157e5fa9fb5320450ea05 (plain)
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
{-# OPTIONS -Wno-type-defaults #-}
module Main where

import Data.List
import Data.Maybe

import Input


closing :: Char -> Maybe Char
closing '(' = Just ')'
closing '[' = Just ']'
closing '{' = Just '}'
closing '<' = Just '>'
closing _ = Nothing

score1 :: Char -> Int
score1 ')' = 3
score1 ']' = 3 * 19
score1 '}' = 3^2 * 7 * 19
score1 '>' = 3^3 * 7^2 * 19
score1 _ = 0

score2 :: Char -> Int
score2 = fromMaybe 0 . fmap succ . flip elemIndex ")]}>"

data Result = SErr Char | Incomplete String | Ok
  deriving (Show)

parse :: String -> Result
parse = go []
  where go s (c : cs) | Just cl <- closing c = go (cl : s) cs
        go (c:s) (c':cs) | c == c' = go s cs
        go _ (c:_) = SErr c
        go s [] = Incomplete s

main :: IO ()
main = do
    inp <- getInput 10
    print $ sum [score1 c | SErr c <- map parse inp]
    let middle l = sort l !! (length l `div` 2)
    print $ middle [sum (zipWith (*) (reverse $ map score2 s) (iterate (*5) 1))
                   | Incomplete s <- map parse inp]