Skip to content

Commit b76f2b8

Browse files
refactor(day3): use a less performant but more readable solution
1 parent da2d6f1 commit b76f2b8

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

Diff for: solutions/Days/Day03.hs

+11-23
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,30 @@
11
module Days.Day03 (day03) where
22

33
import AOC (Solution (..))
4-
import Control.Monad (join)
5-
import Data.Bifunctor (bimap)
64
import Data.Char (isAsciiUpper, isAsciiLower)
5+
import Data.List (foldl1', intersect, nub)
76
import Data.List.Split (chunksOf)
8-
import Data.IntMap.Strict qualified as M
97
import Data.Text qualified as T
108

11-
type Counter = M.IntMap Int
12-
139
day03 :: Solution
1410
day03 = Solution parseInput part1 part2
1511

16-
parseInput :: T.Text -> [T.Text]
17-
parseInput = T.lines
12+
parseInput :: T.Text -> [[Int]]
13+
parseInput = fmap (fmap priority . T.unpack) . T.lines
1814

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
2719

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
3322

3423
priority :: Char -> Int
3524
priority ch
3625
| isAsciiLower ch = fromEnum ch - fromEnum 'a' + 1
3726
| isAsciiUpper ch = fromEnum ch - fromEnum 'A' + 27
3827
| otherwise = error $ show ch
3928

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

Comments
 (0)