aoc-2024-haskell/day1/Main.hs

30 lines
928 B
Haskell
Raw Normal View History

module Main where
import System.Environment (getArgs)
import Data.List (sort)
import Text.Parsec (parse, many, char, endBy)
import Text.ParserCombinators.Parsec (GenParser)
import Text.ParserCombinators.Parsec.Number (decimal)
line :: GenParser Char st (Int, Int)
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)
main :: IO ()
main = do
args <- getArgs
(fp:_) <- return args
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)))