More tidying
[advent-of-code-23.git] / advent06 / Main.hs
1 -- Writeup at https://work.njae.me.uk/2023/12/06/advent-of-code-2023-day-06/
2
3 import AoC
4 import qualified Data.Text as T
5 import qualified Data.Text.IO as TIO
6 import Data.Attoparsec.Text -- hiding (take)
7 -- import Control.Applicative
8
9
10 data Race = Race Int Int deriving (Eq, Show)
11
12 main :: IO ()
13 main =
14 do dataFileName <- getDataFileName
15 text <- TIO.readFile dataFileName
16 let races1 = successfulParse text
17 let races2 = successfulParse $ T.filter (/= ' ') text
18 print $ part1 races1
19 print $ part1 races2
20
21 part1 :: [Race] -> Int
22 part1 = product . fmap waysToWin
23
24 waysToWin :: Race -> Int
25 waysToWin (Race timeLimit record) =
26 length $ filter (> record) [(timeLimit - h) * h | h <- [1..timeLimit]]
27
28 -- Parse the input file
29
30 racesP :: Parser [Race]
31 timesP, distancesP, numbersP :: Parser [Int]
32
33 racesP = zipWith Race <$> (timesP <* endOfLine) <*> distancesP
34 timesP = ("Time:" *> skipSpace) *> numbersP
35 distancesP = ("Distance:" *> skipSpace) *> numbersP
36 numbersP = decimal `sepBy` skipSpace
37
38 successfulParse :: T.Text -> [Race]
39 successfulParse input =
40 case parseOnly racesP input of
41 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
42 Right matches -> matches