r/haskellquestions • • 14d ago

Code Review - Advent of Code 2024 Day 1 Spoiler

Hello hello! I'm quite new to Haskell and I'd decided to try out past Advent of Code puzzles as I progress. My code here works and got the right solution, but I feel a bit dubious about how I handled the input. Any suggestions?

import Data.List
import System.IO

-- Part 1
reconcile :: (Num a, Ord a) => [a] -> [a] -> a
reconcile a b = sum $ zipWith (\x y -> abs $ x - y) (sort a) (sort b)

-- Part 2
similarity :: [Int] -> [Int] -> Int
similarity a b = sum $ map (\id -> id * (length $ filter (== id) b)) a

-- Solutions
main :: IO ()
main = do
  input <- readFile "01-input"
  let list1 = map read [ x | (x:xs) <- map words $ lines input ]
  let list2 = map read [ last xs | xs <- map words $ lines input ]
  print $ reconcile list1 list2
  print $ similarity list1 list2
3 Upvotes

2 comments sorted by

2

u/Axman6 14d ago

What’s the format of the input file? Assuming all lines contain exactly two numbers, I would be inclined to perform a single pass over the lines with something like 

     let (list1, list2) = unzip  [ (x,y) | [x,y] <- map (map read . words) $ lines input ]

similarity could be more efficient, depending on the distribution of the numbers, if you created a map of the counts of each value (Map Int Int) and just look up the value. At the moment you have an O(n2) algorithm because filter is run for every value of list2 over all values of list1, but this change would make it O(n log n). 

I can’t think of a more efficient way to implement reconcile off the top of my head. But it’s type is far more general than you need it to be - not necessarily a problem, but you have already decided it’ll only ever be used on Int lists. 

2

u/mstksg 14d ago

haha seeing this title on my feed gave me a heart attack, like I overslept and missed day 1 of 2026