From 79ed60a4f280321d9fc7c3a8bc1b2e0db705770e Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Tue, 3 Dec 2024 11:54:42 +0000 Subject: [Day 03] Done --- day03/day03.hs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 day03/day03.hs (limited to 'day03/day03.hs') diff --git a/day03/day03.hs b/day03/day03.hs new file mode 100644 index 0000000..4082c24 --- /dev/null +++ b/day03/day03.hs @@ -0,0 +1,44 @@ +import Data.List +import Data.List.Split +import Text.Regex.TDFA +import Text.Regex.TDFA.Text () + +parse :: String -> Int +parse str = + product $ map (read::String->Int) $ getAllTextMatches (str =~ "[0-9]+") + +part1 :: String -> Int +part1 mem = + sum $ map (parse) $ getAllTextMatches (mem =~ "mul\\([0-9]+,[0-9]+\\)") + +data Ins = Do | Dont | Mul Int Int deriving Show + +parse2 :: String -> Ins +parse2 str + | third == '(' = Do + | third == 'n' = Dont + | otherwise = let (f:s:[]) = map (read::String->Int) $ getAllTextMatches (str =~ "[0-9]+") in + Mul f s + where third = head $ tail $ tail str + +execute :: Bool -> Int -> [Ins] -> Int +execute _ sum [] = sum +execute _ sum (Do:rest) = + execute True sum rest +execute _ sum (Dont:rest) = + execute False sum rest +execute True sum (Mul x y:rest) = + execute True (sum + x * y) rest +execute False sum (Mul x y:rest) = + execute False sum rest + +part2 :: String -> Int +part2 mem = + (execute True 0) $ + map (parse2) $ + getAllTextMatches (mem =~ "(mul\\([0-9]+,[0-9]+|do(n't)?\\()\\)") + +main = do + memory <- readFile "day03.input" + putStrLn ("Part 1: " ++ (show $ part1 memory)) + putStrLn ("Part 2: " ++ (show $ part2 memory)) -- cgit v1.2.1