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))