This commit is contained in:
Martin Potier 2020-12-14 14:53:53 +02:00
parent 47bafe66dc
commit 0e498f3caa
No known key found for this signature in database
GPG key ID: D4DD957DBA4AD89E

View file

@ -5,7 +5,7 @@
{-# OPTIONS_GHC -Wall -Wincomplete-uni-patterns #-} {-# OPTIONS_GHC -Wall -Wincomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-imports #-} {-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-imports #-}
{-# OPTIONS_GHC -Wno-unused-matches #-} {-# OPTIONS_GHC -Wno-unused-matches -Wno-type-defaults #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
import Control.Applicative import Control.Applicative
@ -13,27 +13,41 @@ import Data.Attoparsec.Text (Parser)
import Data.Text (Text) import Data.Text (Text)
import Debug.Trace (trace) import Debug.Trace (trace)
import Text.Pretty.Simple import Text.Pretty.Simple
import Data.Maybe (fromMaybe,catMaybes)
import Data.List (find,sortOn)
import qualified Data.Attoparsec.Text as A import qualified Data.Attoparsec.Text as A
import qualified Data.Text as T import qualified Data.Text as T
exampleData :: String exampleData :: String
exampleData = "939\n7,13,x,x,59,x,31,19" exampleData = "939\n7,13,x,x,59,x,31,19"
numOrXParser :: Parser Text numOrXParser :: Parser (Maybe Int)
numOrXParser = A.takeWhile (/= ',') numOrXParser = (Just <$> A.decimal) <|> ("x" *> pure Nothing)
inputParser :: Parser (Int,[Int]) inputParser :: Parser (Int,[Int])
inputParser = do inputParser = do
n <- A.decimal n <- A.decimal
A.skipSpace A.skipSpace
xs <- numOrXParser `A.sepBy` "," xs <- numOrXParser `A.sepBy` ","
pure (n,read <$> T.filter (/= ',') xs) pure (n,catMaybes $ xs)
parseInput :: String -> Either String (Int,[Int]) parseInput :: String -> Either String (Int,[Int])
parseInput = (A.parseOnly inputParser) . T.pack parseInput = (A.parseOnly inputParser) . T.pack
solvePart1 :: String -> Either String Int
solvePart1 str = do
(n,xs) <- parseInput str
let (bus, time) = head
$ sortOn (snd)
$ map (\x -> (x,fromMaybe (-1) $ find (> n) [0,x..])) xs
pure $ bus * (time - n)
main :: IO () main :: IO ()
main = do main = do
putStrLn ":: Test" putStrLn ":: Test"
A.parseTest inputParser $ T.pack exampleData pPrint $ A.parseOnly inputParser $ T.pack exampleData
pPrint $ take 3 ((\n -> [1,n..]) 59)
putStrLn ":: Day 13 - Part 1" putStrLn ":: Day 13 - Part 1"
input <- readFile "day13/input"
pPrint $ solvePart1 exampleData
pPrint $ solvePart1 input