30 lines
799 B
Haskell
30 lines
799 B
Haskell
module Main (main) where
|
|
|
|
import Data.List (sort)
|
|
|
|
-- | Part 1
|
|
extractLists :: String -> ([Int], [Int])
|
|
extractLists = unzip . map ((\[a, b] -> (read a :: Int, read b :: Int)) . words) . lines
|
|
|
|
calculateDifferences :: ([Int], [Int]) -> [Int]
|
|
calculateDifferences (a, b) = zipWith (\n1 n2 -> abs (n1 - n2)) (sort a) (sort b)
|
|
|
|
part1 :: String -> IO ()
|
|
part1 = print . sum . calculateDifferences . extractLists
|
|
|
|
-- | Part 2
|
|
countIn :: [Int] -> Int -> Int
|
|
countIn [] _ = 0
|
|
countIn (x : xs) n
|
|
| n == x = 1 + countIn xs n
|
|
| otherwise = countIn xs n
|
|
|
|
similarityScore :: [Int] -> Int -> Int
|
|
similarityScore l n = n * countIn l n
|
|
|
|
part2 :: String -> IO ()
|
|
part2 = print . sum . (\(a, b) -> map (similarityScore b) a) . extractLists
|
|
|
|
-- | Main
|
|
main :: IO ()
|
|
main = readFile "resources/day1.txt" >>= part2
|