diff options
Diffstat (limited to 'day03/day03.hs')
-rw-r--r-- | day03/day03.hs | 44 |
1 files changed, 44 insertions, 0 deletions
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)) |