From 0d9d0eec00cf8894ebe94ed7b969ece1dae329d6 Mon Sep 17 00:00:00 2001 From: Amneesh Singh Date: Sat, 7 Dec 2024 15:37:24 +0530 Subject: [PATCH] day 7 Signed-off-by: Amneesh Singh --- aoc2024.cabal | 10 +++++++--- src/Day7.hs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 src/Day7.hs diff --git a/aoc2024.cabal b/aoc2024.cabal index 70cdc63..eadbaea 100644 --- a/aoc2024.cabal +++ b/aoc2024.cabal @@ -64,6 +64,10 @@ executable day6 import: common hs-source-dirs: src main-is: Day6.hs - build-depends: - , containers - , libaoc + build-depends: containers + +executable day7 + import: common + hs-source-dirs: src + main-is: Day7.hs + build-depends: libaoc diff --git a/src/Day7.hs b/src/Day7.hs new file mode 100644 index 0000000..4e10802 --- /dev/null +++ b/src/Day7.hs @@ -0,0 +1,48 @@ +module Main where + +import qualified AoC as A (extract) +import Text.Parsec (char, digit, many1, newline, parse, sepBy1, sepEndBy1, string) +import Text.Parsec.String (Parser) + +type Equation = (Int, [Int]) + +type Operator = Int -> Int -> Int + +parseEqns :: Parser [Equation] +parseEqns = parseEqn `sepEndBy1` newline + where + parseEqn :: Parser Equation + parseEqn = + (,) + <$> (read <$> many1 digit <* string ": ") + <*> (read <$> many1 digit) `sepBy1` char ' ' + +-- concatenate integers +cc :: Operator +cc a b = a * (10 ^ length b) + b + where + -- this is faster than log_10 + length :: Int -> Int + length 0 = 0 + length x = 1 + length (x `div` 10) + +check :: [Operator] -> Equation -> Bool +check operators (target, operand : operands) = go operand operands + where + go :: Int -> [Int] -> Bool + go i [] = i == target + go i (x : xs) + | i > target = False -- prune + | otherwise = any (\op -> go (i `op` x) xs) operators + +getSum :: [Operator] -> [Equation] -> Int +getSum ops = sum . map fst . filter (check ops) + +main :: IO () +main = + do + raw <- readFile "./inputs/day7.in" + let equations = A.extract $ parse parseEqns "" raw + + putStr "Part 1: " >> print (getSum [(+), (*)] equations) + putStr "Part 2: " >> print (getSum [(+), (*), cc] equations)