adventofcode-2020/day13/main.hs

54 lines
1.6 KiB
Haskell
Raw Normal View History

2020-12-13 17:50:00 +01:00
#! /usr/bin/env -S"ANSWER=42" nix-shell
#! nix-shell -p ghcid
#! nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [pretty-simple attoparsec])"
#! nix-shell -i "ghcid -c 'ghci' -T main"
{-# OPTIONS_GHC -Wall -Wincomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-imports #-}
2020-12-14 13:53:53 +01:00
{-# OPTIONS_GHC -Wno-unused-matches -Wno-type-defaults #-}
2020-12-13 17:50:00 +01:00
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Attoparsec.Text (Parser)
import Data.Text (Text)
import Debug.Trace (trace)
import Text.Pretty.Simple
2020-12-14 13:53:53 +01:00
import Data.Maybe (fromMaybe,catMaybes)
import Data.List (find,sortOn)
2020-12-13 17:50:00 +01:00
import qualified Data.Attoparsec.Text as A
import qualified Data.Text as T
exampleData :: String
exampleData = "939\n7,13,x,x,59,x,31,19"
2020-12-14 13:53:53 +01:00
numOrXParser :: Parser (Maybe Int)
numOrXParser = (Just <$> A.decimal) <|> ("x" *> pure Nothing)
2020-12-13 17:50:00 +01:00
inputParser :: Parser (Int,[Int])
inputParser = do
n <- A.decimal
A.skipSpace
xs <- numOrXParser `A.sepBy` ","
2020-12-14 13:53:53 +01:00
pure (n,catMaybes $ xs)
2020-12-13 17:50:00 +01:00
parseInput :: String -> Either String (Int,[Int])
parseInput = (A.parseOnly inputParser) . T.pack
2020-12-14 13:53:53 +01:00
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)
2020-12-13 17:50:00 +01:00
main :: IO ()
main = do
putStrLn ":: Test"
2020-12-14 13:53:53 +01:00
pPrint $ A.parseOnly inputParser $ T.pack exampleData
pPrint $ take 3 ((\n -> [1,n..]) 59)
2020-12-13 17:50:00 +01:00
putStrLn ":: Day 13 - Part 1"
2020-12-14 13:53:53 +01:00
input <- readFile "day13/input"
pPrint $ solvePart1 exampleData
pPrint $ solvePart1 input