1 {-# LANGUAGE NegativeLiterals #-}
2 {-# LANGUAGE OverloadedStrings #-}
4 import Data.Text (Text)
5 import qualified Data.Text.IO as TIO
7 import Data.Void (Void)
10 import Text.Megaparsec.Char
11 import qualified Text.Megaparsec.Char.Lexer as L
12 import qualified Control.Applicative as CA
14 import Data.IntSet (IntSet)
15 import qualified Data.IntSet as IntSet
19 text <- TIO.readFile "data/advent01.txt"
20 let changes = successfulParse text
29 part2 changes = snd $ head $ dropWhile unRepeated $ scanl merge (IntSet.empty, 0) $ cycle changes
32 merge :: (IntSet, Int) -> Int -> (IntSet, Int)
33 merge (s, f) c = (IntSet.insert f s, f+c)
35 unRepeated :: (IntSet, Int) -> Bool
36 unRepeated (s, f) = f `IntSet.notMember` s
38 -- Parse the input file
39 type Parser = Parsec Void Text
42 -- sc = L.space (skipSome spaceChar) CA.empty CA.empty
43 sc = L.space (skipSome (char ' ')) CA.empty CA.empty
47 integer = lexeme L.decimal
48 signedInteger = L.signed sc integer
54 changesP = signedInteger `sepEndBy` newline
57 successfulParse :: Text -> [Int]
58 successfulParse input =
59 case parse changesP "input" input of
60 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
61 Right changes -> changes