From f2c85a0f3caf4338314da60dd2c7823a4dad626c Mon Sep 17 00:00:00 2001 From: Neil Smith Date: Wed, 6 Dec 2023 10:06:53 +0000 Subject: [PATCH] Done day 6 --- advent-of-code23.cabal | 5 +++++ advent06/Main.hs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 advent06/Main.hs diff --git a/advent-of-code23.cabal b/advent-of-code23.cabal index 7874bd6..99b2c32 100644 --- a/advent-of-code23.cabal +++ b/advent-of-code23.cabal @@ -130,3 +130,8 @@ executable advent05d import: common-extensions, build-directives main-is: advent05/MainDirect.hs build-depends: text, attoparsec, containers, split + +executable advent06 + import: common-extensions, build-directives + main-is: advent06/Main.hs + build-depends: text, attoparsec diff --git a/advent06/Main.hs b/advent06/Main.hs new file mode 100644 index 0000000..2a056bb --- /dev/null +++ b/advent06/Main.hs @@ -0,0 +1,42 @@ +-- Writeup at https://work.njae.me.uk/2023/12/06/advent-of-code-2023-day-06/ + +import AoC +import qualified Data.Text as T +import qualified Data.Text.IO as TIO +import Data.Attoparsec.Text -- hiding (take) +-- import Control.Applicative + + +data Race = Race Int Int deriving (Eq, Show) + +main :: IO () +main = + do dataFileName <- getDataFileName + text <- TIO.readFile dataFileName + let races1 = successfulParse text + let races2 = successfulParse $ T.filter (/= ' ') text + print $ part1 races1 + print $ part1 races2 + +part1 :: [Race] -> Int +part1 = product . fmap waysToWin + +waysToWin :: Race -> Int +waysToWin (Race timeLimit record) = + length $ filter (> record) [(timeLimit - h) * h | h <- [1..timeLimit]] + +-- Parse the input file + +racesP :: Parser [Race] +timesP, distancesP, numbersP :: Parser [Int] + +racesP = zipWith Race <$> (timesP <* endOfLine) <*> distancesP +timesP = ("Time:" *> skipSpace) *> numbersP +distancesP = ("Distance:" *> skipSpace) *> numbersP +numbersP = decimal `sepBy` skipSpace + +successfulParse :: T.Text -> [Race] +successfulParse input = + case parseOnly racesP input of + Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err + Right matches -> matches -- 2.34.1