From 38ff90154f071fa83a702858cd506f7f3011cdf4 Mon Sep 17 00:00:00 2001 From: kale Date: Tue, 3 Dec 2024 17:39:36 +0100 Subject: [PATCH] feat(day1): Implement part2 --- day1/Main.hs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/day1/Main.hs b/day1/Main.hs index e4ec69b..ab2ed06 100644 --- a/day1/Main.hs +++ b/day1/Main.hs @@ -3,6 +3,7 @@ module Main where import System.Environment (getArgs) import Data.List (sort) +import Data.Function (on) import Text.Parsec (parse, many, char, endBy) import Text.ParserCombinators.Parsec (GenParser) @@ -14,8 +15,11 @@ line = decimal >>= \l -> many (char ' ') >> decimal >>= \r -> return (l, r) locationIDs :: GenParser Char st [(Int, Int)] locationIDs = endBy line (char '\n') -computeDistance :: [Int] -> [Int] -> Int -computeDistance l r = sum (zipWith (curry (abs . uncurry (-))) l r) +part1 :: [Int] -> [Int] -> Int +part1 l r = sum (zipWith (curry (abs . uncurry (-))) l r) + +part2 :: [Int] -> [Int] -> Int +part2 l r = (sum . map (\x -> sum ((map (const x) . filter (==x)) r))) l main :: IO () main = do @@ -24,6 +28,7 @@ main = do content <- readFile fp case parse locationIDs fp content of Left e -> putStrLn ("Input file is incorrectly formatted : " ++ show e) - Right ids -> let (l, r) = unzip ids - in putStrLn ("Solution (Part 1) : " - ++ show (computeDistance (sort l) (sort r))) + Right ids -> do + let (ls, rs) = uncurry ((,) `on` sort) (unzip ids) + putStrLn ("Solution (Part 1) : " ++ show (part1 ls rs)) + putStrLn ("Solution (Part 2) : " ++ show (part2 ls rs))