From 2cb456a7c429cab5207f63cb238c8893214bf36b Mon Sep 17 00:00:00 2001 From: Amneesh Singh Date: Fri, 13 Dec 2024 20:05:34 +0530 Subject: [PATCH] day 13 Signed-off-by: Amneesh Singh --- aoc2024.cabal | 6 +++++ src/Day13.hs | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/Day13.hs diff --git a/aoc2024.cabal b/aoc2024.cabal index 3191d13..e4d90bc 100644 --- a/aoc2024.cabal +++ b/aoc2024.cabal @@ -102,3 +102,9 @@ executable day12 hs-source-dirs: src main-is: Day12.hs build-depends: containers + +executable day13 + import: common + hs-source-dirs: src + main-is: Day13.hs + build-depends: libaoc diff --git a/src/Day13.hs b/src/Day13.hs new file mode 100644 index 0000000..80cf468 --- /dev/null +++ b/src/Day13.hs @@ -0,0 +1,69 @@ +module Main where + +import qualified AoC as A (extract) +import Control.Monad (void) +import Text.Parsec (digit, eof, many1, newline, parse, sepBy1, string, try, (<|>)) +import Text.Parsec.String (Parser) + +type Pair = (Int, Int) + +type Conf = (Pair, Pair, Pair) + +parseConfs :: Parser [Conf] +parseConfs = parseConf `sepBy1` newline + where + parseConf :: Parser Conf + parseConf = do + ax <- string "Button A: X+" *> (read <$> many1 digit) + ay <- string ", Y+" *> (read <$> many1 digit) + _ <- newline + + bx <- string "Button B: X+" *> (read <$> many1 digit) + by <- string ", Y+" *> (read <$> many1 digit) + _ <- newline + + px <- string "Prize: X=" *> (read <$> many1 digit) + py <- string ", Y=" *> (read <$> many1 digit) + try (void newline <|> eof) + + return ((ax, ay), (bx, by), (px, py)) + +-- the matrix is never singular somehow, wtf aoc! +soln :: Conf -> Maybe (Int, Int) +soln ((ax, ay), (bx, by), (cx, cy)) + | det == 0 = error "Singular Matrix Encountered, |A| = 0" + | (b, 0) <- (cy * ax - cx * ay) `quotRem` det, -- remainder 0 for integer solns + (a, 0) <- (cy - by * b) `quotRem` ay = + Just (a, b) + | otherwise = Nothing + where + det = ax * by - bx * ay + +part1 :: [Conf] -> Int +part1 confs = + sum + [ 3 * a + b + | conf <- confs, + Just (a, b) <- [soln conf], + a <= 100 && b <= 100 + ] + +transform :: Conf -> Conf +transform (a, b, (x, y)) = (a, b, (x + 10000000000000, y + 10000000000000)) + +part2 :: [Conf] -> Int +part2 confs = + sum + [ 3 * a + b + | conf <- map transform confs, + Just (a, b) <- [soln conf] + ] + +main :: IO () +main = + do + raw <- readFile "./inputs/day13.in" + let confs = A.extract $ parse parseConfs "" raw + + putStr "Part 1: " >> print (part1 confs) + putStr "Part 2: " >> print (part2 confs)