-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.hs
58 lines (46 loc) · 1.2 KB
/
run.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
54
55
56
57
58
{-# LANGUAGE TypeApplications #-}
import Data.List (findIndices, sort, elemIndices)
import Data.List.Split (chunksOf)
import Control.Applicative ((<|>))
import Text.Read (readListPrec, readPrec)
data Tree = Leaf Int
| Branch [Tree]
deriving (Eq, Show)
instance Read Tree where
readPrec = (Leaf <$> readPrec @Int)
<|> (Branch <$> readListPrec @Tree)
instance Ord Tree where
compare t1 t2 =
case (t1, t2) of
(Leaf n1, Leaf n2) -> compare n1 n2
(Branch x1, Branch x2) -> compare x1 x2
(Leaf n1, Branch x2) -> compare [Leaf n1] x2
(Branch x1, Leaf n2) -> compare x1 [Leaf n2]
parse :: String -> Tree
parse = read
parseAll :: String -> [Tree]
parseAll =
map parse
. filter (not . null)
. lines
part1 :: [Tree] -> Int
part1 =
sum
. map (+1)
. elemIndices LT
. map (\[x1, x2] -> compare x1 x2)
. chunksOf 2
dividers :: [Tree]
dividers = map read
[ "[[2]]"
, "[[6]]"
]
part2 :: [Tree] -> Int
part2 = product . map (+1) . findIndices (`elem` dividers) . sort . (<> dividers)
main :: IO ()
main = main' "input.txt"
main' :: FilePath -> IO ()
main' file = do
input <- parseAll <$> readFile file
print (part1 input)
print (part2 input)