X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=advent06%2FMain.hs;fp=advent06%2FMain.hs;h=2a056bb9f14c00e63acc69e8ab61e6865bbb5dee;hb=f2c85a0f3caf4338314da60dd2c7823a4dad626c;hp=0000000000000000000000000000000000000000;hpb=1599e58ce29dd3ae6a2e0945d5f78c409295703a;p=advent-of-code-23.git 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