feat(day1): Implement part2

This commit is contained in:
kale 2024-12-03 17:39:36 +01:00
parent 05f4bc61cb
commit 38ff90154f
Signed by: kalmenn
GPG key ID: F500055C44BC3834

View file

@ -3,6 +3,7 @@ module Main where
import System.Environment (getArgs) import System.Environment (getArgs)
import Data.List (sort) import Data.List (sort)
import Data.Function (on)
import Text.Parsec (parse, many, char, endBy) import Text.Parsec (parse, many, char, endBy)
import Text.ParserCombinators.Parsec (GenParser) 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 :: GenParser Char st [(Int, Int)]
locationIDs = endBy line (char '\n') locationIDs = endBy line (char '\n')
computeDistance :: [Int] -> [Int] -> Int part1 :: [Int] -> [Int] -> Int
computeDistance l r = sum (zipWith (curry (abs . uncurry (-))) l r) 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 :: IO ()
main = do main = do
@ -24,6 +28,7 @@ main = do
content <- readFile fp content <- readFile fp
case parse locationIDs fp content of case parse locationIDs fp content of
Left e -> putStrLn ("Input file is incorrectly formatted : " ++ show e) Left e -> putStrLn ("Input file is incorrectly formatted : " ++ show e)
Right ids -> let (l, r) = unzip ids Right ids -> do
in putStrLn ("Solution (Part 1) : " let (ls, rs) = uncurry ((,) `on` sort) (unzip ids)
++ show (computeDistance (sort l) (sort r))) putStrLn ("Solution (Part 1) : " ++ show (part1 ls rs))
putStrLn ("Solution (Part 2) : " ++ show (part2 ls rs))