/
Day03.hs
64 lines (45 loc) · 1.35 KB
/
Day03.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
59
60
61
62
63
64
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeApplications #-}
module Day03 where
import Data.Char
import Data.Function (on)
import Text.ParserCombinators.ReadP
import Harness
import ParseHelper
import qualified Data.List as L
main :: IO ()
main =
getInputAndSolve
(parseInput parseSack)
commonItemsPriority
elfGroupPriority
-- SOLVE
commonItemsPriority :: [Sack] -> Int
commonItemsPriority = sum . map (toPriority . findCommon)
where
findCommon :: Sack -> Char
findCommon (Sack items) =
let (firstCompartment, secondCompartment) =
L.splitAt (length items `div` 2) items
in head $ firstCompartment `L.intersect` secondCompartment
elfGroupPriority :: [Sack] -> Int
elfGroupPriority =
sum
. map (toPriority . findCommon . map snd)
. L.groupBy ((==) @Integer `on` (`div` 3) . fst)
. zip [0 ..]
where
findCommon :: [Sack] -> Char
findCommon = \case
[Sack a, Sack b, Sack c] ->
head $ a `L.intersect` b `L.intersect` c
err -> error $ "Group w/ length not 3: " <> show err
-- HELPERS
toPriority :: Char -> Int
toPriority c
| isAsciiLower c = fromEnum c - 96
| otherwise = fromEnum c - 38
-- PARSE
newtype Sack = Sack [Char] deriving (Show, Read, Eq, Ord)
parseSack :: ReadP Sack
parseSack = Sack <$> many (satisfy isAlpha)