Done part 2, needs tidying
[advent-of-code-23.git] / advent01 / Main.hs
index 9bdb587dcfcc344a70c40a7675c9810111df245a..f4192a97312a515e1005436e4b2ed2d58d945a6a 100644 (file)
@@ -1,10 +1,8 @@
--- Writeup at https://work.njae.me.uk/advent-of-code-2023-day-01/
+-- Writeup at https://work.njae.me.uk/2023/12/01/advent-of-code-2023-day-01/
 
 import AoC
 import Data.Char
 import Data.List
-import Data.List.Split
-
 
 main :: IO ()
 main = 
@@ -26,17 +24,17 @@ getCalibration calibration = read [head digits, last digits]
   where digits = filter isDigit calibration
 
 replaceNums :: String -> String
-replaceNums [] = []
-replaceNums haystack 
-  | "one"   `isPrefixOf` haystack = '1' : remainder
-  | "two"   `isPrefixOf` haystack = '2' : remainder
-  | "three" `isPrefixOf` haystack = '3' : remainder
-  | "four"  `isPrefixOf` haystack = '4' : remainder
-  | "five"  `isPrefixOf` haystack = '5' : remainder
-  | "six"   `isPrefixOf` haystack = '6' : remainder
-  | "seven" `isPrefixOf` haystack = '7' : remainder
-  | "eight" `isPrefixOf` haystack = '8' : remainder
-  | "nine"  `isPrefixOf` haystack = '9' : remainder
-  | otherwise = (head haystack) : remainder
-  where remainder = replaceNums $ tail haystack
-
+replaceNums haystack = reverse $ foldl' go "" $ tails haystack
+  where go acc [] = acc
+        go acc xs 
+          | "one"   `isPrefixOf` xs = '1' : acc
+          | "two"   `isPrefixOf` xs = '2' : acc
+          | "three" `isPrefixOf` xs = '3' : acc
+          | "four"  `isPrefixOf` xs = '4' : acc
+          | "five"  `isPrefixOf` xs = '5' : acc
+          | "six"   `isPrefixOf` xs = '6' : acc
+          | "seven" `isPrefixOf` xs = '7' : acc
+          | "eight" `isPrefixOf` xs = '8' : acc
+          | "nine"  `isPrefixOf` xs = '9' : acc
+          | isDigit (head xs) = (head xs) : acc
+          | otherwise = acc