Advent of Code 2026 Day 1
Puzzle: 2026 day 1 · Code: Day1.hs
Initial Thoughts
- we can create a
Mapof frequencies, so something likeMap Item Frequency - and then just sort it by frequency to get the top 3 keys
- there’s surely a more single-pass kind of way to do it but for a small input we don’t need it!
Code for Part 1
module Day1 where
import Data.List (sortOn)
import qualified Data.Map as M
import Utils.Grouping (frequencies)
part1 :: IO Int
part1 = product . take 3 . map fst . sortOn ((* (-1)) . snd) . M.toList . frequencies <$> getInput
getInput :: IO [Int]
getInput = map read . lines <$> readFile "./fixtures/input1.txt"
where I’ve used a helper from a previous year
frequencies :: (Ord a) => [a] -> Map a Int
frequencies = foldr incrementMap empty
where
incrementMap x = insertWith (+) x 1
Initial Thoughts on Part 2
- this is the same as my
part1but I just need to flip the sort order
Code for Part 2
part2 :: IO Int
part2 = product . take 3 . map fst . sortOn (snd) . M.toList . frequencies <$> getInput
Final Thoughts
- this was a nice warm up
- I really like that both parts are nice one liners here!
- the leap from
part1topart2was very simple - I find my
sortOn ((* (-1)) . snd)a little ugly though- In scala I’d do something like
Ordering[Int].reverse - so in Haskell I can use
import Data.Ord (Down (..))
- In scala I’d do something like
- In general this is surely possible without having to use a sort at all, but it’s not really necessary for me
- I suppose I could generalise since
part1andpart2differ only by the sort function but I don’t feel the need to
Final Full Solution
module Day1 where
import Data.List (sortOn)
import qualified Data.Map as M
import Data.Ord (Down (..))
import Utils.Grouping (frequencies)
part1 :: IO Int
part1 = product . take 3 . map fst . sortOn (Down . snd) . M.toList . frequencies <$> getInput
part2 :: IO Int
part2 = product . take 3 . map fst . sortOn (snd) . M.toList . frequencies <$> getInput
getInput :: IO [Int]
getInput = map read . lines <$> readFile "./fixtures/input1.txt"