summaryrefslogtreecommitdiff
path: root/day03/day03.hs
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2024-12-03 11:54:42 +0000
committerNat Lasseter <user@4574.co.uk>2024-12-03 11:54:42 +0000
commit79ed60a4f280321d9fc7c3a8bc1b2e0db705770e (patch)
treef5a7bf78e50efb8ed6d35fc843ca7fc1d6f25951 /day03/day03.hs
parentfe4cf97411f1e7f3aa23aac7bfbc3cebbd2af82d (diff)
[Day 03] Done
Diffstat (limited to 'day03/day03.hs')
-rw-r--r--day03/day03.hs44
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))