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