Done day 6
[advent-of-code-23.git] / advent06 / Main.hs
diff --git a/advent06/Main.hs b/advent06/Main.hs
new file mode 100644 (file)
index 0000000..2a056bb
--- /dev/null
@@ -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