feat(day1): Implement part2
This commit is contained in:
parent
05f4bc61cb
commit
38ff90154f
15
day1/Main.hs
15
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))
|
||||
|
|
Loading…
Reference in a new issue