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
--- /dev/null
+-- 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