|
1 | 1 | module Days.Day03 (day03) where
|
2 | 2 |
|
3 | 3 | import AOC (Solution (..))
|
4 |
| -import Control.Monad (join) |
5 |
| -import Data.Bifunctor (bimap) |
6 | 4 | import Data.Char (isAsciiUpper, isAsciiLower)
|
| 5 | +import Data.List (foldl1', intersect, nub) |
7 | 6 | import Data.List.Split (chunksOf)
|
8 |
| -import Data.IntMap.Strict qualified as M |
9 | 7 | import Data.Text qualified as T
|
10 | 8 |
|
11 |
| -type Counter = M.IntMap Int |
12 |
| - |
13 | 9 | day03 :: Solution
|
14 | 10 | day03 = Solution parseInput part1 part2
|
15 | 11 |
|
16 |
| -parseInput :: T.Text -> [T.Text] |
17 |
| -parseInput = T.lines |
| 12 | +parseInput :: T.Text -> [[Int]] |
| 13 | +parseInput = fmap (fmap priority . T.unpack) . T.lines |
18 | 14 |
|
19 |
| -part1 :: [T.Text] -> Int |
20 |
| -part1 = sum |
21 |
| - . fmap (fst |
22 |
| - . head |
23 |
| - . M.toList |
24 |
| - . uncurry M.intersection |
25 |
| - . join bimap mkCounter |
26 |
| - . (T.splitAt =<< ((`div` 2) . T.length))) |
| 15 | +part1 :: [[Int]] -> Int |
| 16 | +part1 = sum . concatMap (intersections . halve) |
| 17 | + where |
| 18 | + halve xs = chunksOf (length xs `div` 2) xs |
27 | 19 |
|
28 |
| -part2 :: [T.Text] -> Int |
29 |
| -part2 = sum |
30 |
| - . fmap (fst . head . M.toList . foldr1 M.intersection) |
31 |
| - . chunksOf 3 |
32 |
| - . fmap mkCounter |
| 20 | +part2 :: [[Int]] -> Int |
| 21 | +part2 = sum . concatMap intersections . chunksOf 3 |
33 | 22 |
|
34 | 23 | priority :: Char -> Int
|
35 | 24 | priority ch
|
36 | 25 | | isAsciiLower ch = fromEnum ch - fromEnum 'a' + 1
|
37 | 26 | | isAsciiUpper ch = fromEnum ch - fromEnum 'A' + 27
|
38 | 27 | | otherwise = error $ show ch
|
39 | 28 |
|
40 |
| -mkCounter :: T.Text -> Counter |
41 |
| -mkCounter = |
42 |
| - M.fromListWith (+) . flip zip [1,1..] . fmap priority . T.unpack |
| 29 | +intersections :: Eq a => [[a]] -> [a] |
| 30 | +intersections = nub . foldl1' intersect |
0 commit comments