summaryrefslogtreecommitdiff
path: root/day03/day03.hs
blob: 4082c24faebcd1461b31ff9d167bfdec5b13447f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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))