Compare commits

...

1 Commits

Author SHA1 Message Date
Gaël Depreeuw 47c1560549
Solve day 4, part 1 4 years ago
  1. 2
      AdventOfCode2020.cabal
  2. 2
      Main.hs
  3. 1009
      input/day4
  4. 75
      src/Day4.hs

@ -17,7 +17,7 @@ maintainer: gael@depreeuw.dev
extra-source-files: CHANGELOG.md, README.md
library
exposed-modules: Day1, Day2, Day3
exposed-modules: Day1, Day2, Day3, Day4
-- other-modules:
-- other-extensions:
build-depends: base ^>=4.13.0.0

@ -3,9 +3,11 @@ module Main where
import Day1 (day1)
import Day2 (day2)
import Day3 (day3)
import Day4 (day4)
main :: IO ()
main = do
day1
day2
day3
day4

File diff suppressed because it is too large Load Diff

@ -0,0 +1,75 @@
{-# LANGUAGE OverloadedStrings #-}
module Day4 (day4) where
import Control.Applicative ((<|>))
import Control.Monad (void)
import qualified Data.Attoparsec.Text as P
import qualified Data.Map as M
import Data.Maybe (catMaybes)
import qualified Data.Text as T
type BYR = T.Text
type IYR = T.Text
type EYR = T.Text
type HGT = T.Text
type HCL = T.Text
type ECL = T.Text
type PID = T.Text
type CID = T.Text
data Passport = ValidPassport
{ byr :: BYR,
iyr :: IYR,
eyr :: EYR,
hgt :: HGT,
hcl :: HCL,
ecl :: ECL,
pid :: PID,
cid :: Maybe CID -- Definitely not a hack!
}
deriving (Eq, Show)
parserPair :: P.Parser (T.Text, T.Text)
parserPair = do
key <- P.count 3 P.letter
_ <- P.char ':'
value <- P.takeWhile1 (P.inClass "a-zA-Z0-9#")
return (T.pack key, value)
parserEntry :: P.Parser (M.Map T.Text T.Text)
parserEntry = M.fromList <$> parserPair `P.sepBy` (void P.space <|> P.endOfLine)
fromMap :: M.Map T.Text T.Text -> Maybe Passport
fromMap m = do
byr <- m M.!? "byr"
iyr <- m M.!? "iyr"
eyr <- m M.!? "eyr"
hgt <- m M.!? "hgt"
hcl <- m M.!? "hcl"
ecl <- m M.!? "ecl"
pid <- m M.!? "pid"
return $ ValidPassport byr iyr eyr hgt hcl ecl pid (m M.!? "cid")
parserPassport :: P.Parser (Maybe Passport)
parserPassport = fromMap <$> parserEntry
parseList :: String -> [Maybe Passport]
parseList s =
let p = parserPassport `P.sepBy` P.endOfLine
in case P.parseOnly p (T.pack s) of
Left s -> error (show s)
Right r -> r
day4 :: IO ()
day4 = do
r <- readFile "./input/day4"
putStr "[Day 4-1] # trees: "
print . length . catMaybes . parseList $ r
Loading…
Cancel
Save