Done day 11
[advent-of-code-22.git] / advent03 / Main.hs
1 -- Writeup at https://work.njae.me.uk/2022/12/03/advent-of-code-2022-day-3/
2
3 import AoC
4 import Data.Char
5 import qualified Data.Set as S
6 import Data.List
7 import Data.List.Split
8
9 type Contents = S.Set Char
10 data Rucksack = Rucksack String String deriving (Show, Eq)
11
12 main :: IO ()
13 main =
14 do dataFileName <- getDataFileName
15 text <- readFile dataFileName
16 let rucksacks = fmap mkRucksack $ lines text
17 print $ part1 rucksacks
18 print $ part2 rucksacks
19
20 part1 :: [Rucksack] -> Int
21 part1 = sum . fmap (priority . commonItem)
22
23 part2 :: [Rucksack] -> Int
24 part2 rucksacks = sum $ fmap priority badges
25 where groups = chunksOf 3 rucksacks
26 badges = fmap badgeOf groups
27
28 merge :: Rucksack -> Contents
29 merge (Rucksack contents1 contents2) =
30 S.union (S.fromList contents1) (S.fromList contents2)
31
32 badgeOf :: [Rucksack] -> Char
33 badgeOf rucksacks = S.findMin $ intersections (fmap merge rucksacks)
34
35 intersections :: [Contents] -> Contents
36 intersections sets = foldl1' S.intersection sets
37
38
39 mkRucksack :: String -> Rucksack
40 mkRucksack contents = Rucksack (take n contents) (drop n contents)
41 where n = length contents `div` 2
42
43 commonItem :: Rucksack -> Char
44 commonItem (Rucksack contents1 contents2) = S.findMin (c1 `S.intersection` c2)
45 where c1 = S.fromList contents1
46 c2 = S.fromList contents2
47
48 priority :: Char -> Int
49 priority item
50 | isLower item = ord item - ord 'a' + 1
51 | otherwise = ord item - ord 'A' + 27