summary refs log tree commit diff
path: root/src/Day1.idr
blob: e29b0a7eff9fd71cd932d3d3f40275477086feb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Day1

import System
import System.File
import Data.String
import Text.Parser

parsePair : String -> Maybe (Int, Int)
parsePair pair = do
  num1 <- parseInteger (fst p1)
  num2 <- parseInteger (snd p2)
  pure (num1, num2) where
  p1 = span (/= ' ') pair
  p2 = span (== ' ') (snd p1)

parseStr : String -> List (Int, Int)
parseStr str = do
  nums <- lines str
  maybe [] pure (parsePair nums)
  
part1 : (List Int, List Int) -> Int
part1 inp = sum $ zipWith (\x => \y => abs (x - y)) (sort $ fst inp) (sort $ snd inp)

occur : Eq a => Num b => a -> List a -> b
occur x fs = foldr (\y => \r =>  if x == y then r + 1 else r) 0 fs

part2 : (List Int, List Int) -> Int
part2 (l1, l2) = sum $ map (\x => x * (occur x l2)) l1

export
sol1 : String -> String
sol1 = show . part1 . unzip . parseStr

export
sol2 : String -> String
sol2 = show . part2 . unzip . parseStr