aoc/app/3.hs
2024-12-03 12:52:47 +01:00

33 lines
893 B
Haskell

{-# LANGUAGE LambdaCase #-}
module Main where
import Text.Regex.TDFA
import Data.List.Split
e :: [String] -> [(Int,Int)]
e = ((\case
[a,b] -> (read a, read b)
err -> error $ "Parsing failed on: " ++ show err
) . splitWhen (== ',') . init . drop 4 <$>)
parse1 :: String -> [(Int,Int)]
parse1 = e . getAllTextMatches . (=~ "mul\\([[:digit:]]+,[[:digit:]]+\\)")
parse2 :: String -> [(Int,Int)]
parse2 =
let h [] = []
h a = let (t,t') = span (/= "don't()") a in t ++ g t'
g [] = []
g a = h . dropWhile (== "do()") $ dropWhile (/= "do()") a in
e . filter (/= "do()") . h .
getAllTextMatches . (=~ "mul\\([[:digit:]]+,[[:digit:]]+\\)|do\\(\\)|don't\\(\\)")
solve :: [(Int,Int)] -> Int
solve = foldr ((+) . uncurry (*)) 0
main :: IO ()
main = readFile "inputs/3" >>= \i ->
print (solve $ parse1 i) >>
print (solve $ parse2 i)