1 -- Writeup at https://work.njae.me.uk/2022/12/04/advent-of-code-2022-day-4/
4 import Data.Text (Text)
5 import qualified Data.Text.IO as TIO
6 import Data.Attoparsec.Text hiding (Result)
7 import Numeric.Interval hiding (null)
8 -- import Control.Applicative
10 type Assignment = Interval Int
11 type Pair = (Assignment, Assignment)
15 do dataFileName <- getDataFileName
16 text <- TIO.readFile dataFileName
17 let pairs = successfulParse text
21 part1 :: [Pair] -> Int
22 part1 = length . (filter hasContainment)
24 part2 :: [Pair] -> Int
25 part2 = length . (filter $ uncurry (==?))
27 hasContainment :: Pair -> Bool
28 hasContainment (assignment1, assignment2) =
29 (assignment1 `contains` assignment2) || (assignment2 `contains` assignment1)
32 -- Parse the input file
34 pairsP :: Parser [Pair]
36 assignmentP :: Parser Assignment
38 pairsP = pairP `sepBy` endOfLine
39 pairP = (,) <$> assignmentP <* "," <*> assignmentP
41 assignmentP = (...) <$> decimal <* "-" <*> decimal
43 successfulParse :: Text -> [Pair]
44 successfulParse input =
45 case parseOnly pairsP input of
46 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err