Haskell for Advent of Code (Day 1)
I am going to try and fullsolve Advent of Code entirely in Haskell. I’ve been reading Hutton’s Programming in Haskell over the past few days. I was able to quickly breeze through part 1, but understanding part 2 has proven to be quite difficult. I still don’t know what a monad is.
Something that the book doesn’t cover is syntatic sugar for not having to do bracket spam by using the .
and $
operators. It is described in this stack overflow post.
Hoogle is also really helpful to look up library functions. transpose
really saved me today, I still had to spend a few hours to fiddle around with a few lines of code… Anyways here is my code for day 1.
import System.IO
import Data.List
cnt :: [Int] -> Int -> Int
cnt as v = length ( filter (== v) as )
main :: IO()
main = do inp <- getContents
print $ sum $ map (\(a:b:_) -> abs (a-b)) $ transpose $ map sort $ transpose $ map (\x -> map read (words x)) $ lines inp
let as:bs:_ = transpose $ map (\x -> map read (words x)) $ lines inp
print $ sum $ zipWith (*) as $ map (cnt bs) as