advent06.hs 986 Bytes
Newer Older
Neil Smith's avatar
Neil Smith committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
-- import Debug.Trace

import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

import Data.Attoparsec.Text
-- import Data.Attoparsec.Combinator

import qualified Data.Set as S

main :: IO ()
main = 
  do  text <- TIO.readFile "data/advent06.txt"
      let groups = successfulParse text
      -- print groups
      print $ part1 groups
      print $ part2 groups

part1 groups = sum $ map (S.size . S.unions) groups
part2 groups = sum $ map (S.size . intersections) groups

intersections :: Ord a => [S.Set a] -> S.Set a
intersections group = foldl S.intersection (head group) group

-- -- Parse the input file

blankLines = skipMany1 endOfLine

personP = S.fromList <$> many1 letter
groupP = sepBy1 personP endOfLine

Neil Smith's avatar
Neil Smith committed
33
groupsP = sepBy groupP blankLines
Neil Smith's avatar
Neil Smith committed
34

Neil Smith's avatar
Neil Smith committed
35
successfulParse :: Text -> [[S.Set Char]]
Neil Smith's avatar
Neil Smith committed
36 37 38 39
successfulParse input = 
  case parseOnly groupsP input of
    Left  _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
    Right groups -> groups