2023 day 6 in Haskell
\# time cabal run < input >/dev/null cabal run < input > /dev/null 0.19s user 0.01s system 97% cpu 0.210 total
This commit is contained in:
parent
9dcc8c49de
commit
2845d77b9b
|
@ -0,0 +1,20 @@
|
|||
cabal-version: 3.0
|
||||
name: Day06
|
||||
version: 0.1.0.0
|
||||
license: NONE
|
||||
build-type: Simple
|
||||
extra-doc-files: CHANGELOG.md
|
||||
|
||||
common warnings
|
||||
ghc-options: -Wall
|
||||
|
||||
executable Day06
|
||||
import: warnings
|
||||
main-is: Day06.hs
|
||||
build-depends: base ^>=4.17.2.1
|
||||
, attoparsec ^>=0.14.4
|
||||
, text ^>=2.1
|
||||
, containers ^>=0.6.7
|
||||
, digits ^>=0.3.1
|
||||
hs-source-dirs: .
|
||||
default-language: Haskell2010
|
|
@ -0,0 +1,47 @@
|
|||
{-# LANGUAGE OverloadedStrings #-}
|
||||
module Main where
|
||||
|
||||
import qualified Data.Text as T
|
||||
import qualified Data.Text.IO as TIO
|
||||
|
||||
import Data.Digits (digits, unDigits)
|
||||
import Data.Attoparsec.Text
|
||||
|
||||
type Time = Int
|
||||
type Distance = Int
|
||||
type Input = [(Time, Distance)]
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
input <- TIO.getContents >>= parseInput
|
||||
putStrLn ("Part 1: " <> show (part1 input))
|
||||
putStrLn ("Part 2: " <> show (part2 input))
|
||||
|
||||
parseInput :: T.Text -> IO Input
|
||||
parseInput s = case parseOnly inputParser s of
|
||||
Right i -> pure i
|
||||
Left e -> error e
|
||||
|
||||
inputParser :: Parser Input
|
||||
inputParser = do
|
||||
times <- string "Time: " *> numList
|
||||
distances <- string "Distance: " *> numList <* skipSpace <* endOfInput
|
||||
return $ zip times distances
|
||||
|
||||
numList :: Parser [Int]
|
||||
numList = skipSpace *> sepBy1 decimal skipSpace <* endOfLine
|
||||
|
||||
travelledDistance :: Int -> Int -> Int
|
||||
travelledDistance charge maxTime = (maxTime - charge) * charge
|
||||
|
||||
winningOptions :: (Time, Distance) -> Int
|
||||
winningOptions (t, d) = length $ filter (\x -> travelledDistance x t > d) [1..t - 1]
|
||||
|
||||
part1 :: Input -> Int
|
||||
part1 = product . map winningOptions
|
||||
|
||||
part2 :: Input -> Int
|
||||
part2 i = winningOptions (joinNumbers $ map fst i, joinNumbers $ map snd i)
|
||||
|
||||
joinNumbers :: [Int] -> Int
|
||||
joinNumbers = unDigits 10 . foldMap (digits 10)
|
|
@ -0,0 +1,2 @@
|
|||
Time: 7 15 30
|
||||
Distance: 9 40 200
|
Loading…
Reference in New Issue