Updated README
[advent-of-code-23.git] / advent01 / Main.hs
1 -- Writeup at https://work.njae.me.uk/advent-of-code-2023-day-01/
2
3 import AoC
4 import Data.Char
5 import Data.List
6 import Data.List.Split
7
8
9 main :: IO ()
10 main =
11 do dataFileName <- getDataFileName
12 cals <- readFile dataFileName
13 let calibrations = lines cals
14 print $ part1 calibrations
15 print $ part2 calibrations
16
17 part1 :: [String] -> Int
18 -- part1 calibrations = sum $ fmap getCalibration calibrations
19 part1 = sum . (fmap getCalibration)
20
21 part2 :: [String] -> Int
22 part2 calibrations = sum $ fmap (getCalibration . replaceNums) calibrations
23
24 getCalibration :: String -> Int
25 getCalibration calibration = read [head digits, last digits]
26 where digits = filter isDigit calibration
27
28 replaceNums :: String -> String
29 replaceNums [] = []
30 replaceNums haystack
31 | "one" `isPrefixOf` haystack = '1' : remainder
32 | "two" `isPrefixOf` haystack = '2' : remainder
33 | "three" `isPrefixOf` haystack = '3' : remainder
34 | "four" `isPrefixOf` haystack = '4' : remainder
35 | "five" `isPrefixOf` haystack = '5' : remainder
36 | "six" `isPrefixOf` haystack = '6' : remainder
37 | "seven" `isPrefixOf` haystack = '7' : remainder
38 | "eight" `isPrefixOf` haystack = '8' : remainder
39 | "nine" `isPrefixOf` haystack = '9' : remainder
40 | otherwise = (head haystack) : remainder
41 where remainder = replaceNums $ tail haystack
42