Initial file structure set up.
[advent-of-code-19.git] / advent01 / src / advent01.hs
1 {-# LANGUAGE NegativeLiterals #-}
2 {-# LANGUAGE OverloadedStrings #-}
3
4 import Data.Text (Text)
5 import qualified Data.Text.IO as TIO
6
7 import Data.Void (Void)
8
9 import Text.Megaparsec
10 import Text.Megaparsec.Char
11 import qualified Text.Megaparsec.Char.Lexer as L
12 import qualified Control.Applicative as CA
13
14 import Data.IntSet (IntSet)
15 import qualified Data.IntSet as S
16
17 main :: IO ()
18 main = do
19 text <- TIO.readFile "data/advent01.txt"
20 let changes = successfulParse text
21 print $ part1 changes
22 print $ part2 changes
23
24
25 part1 :: [Int] -> Int
26 part1 = sum
27
28 part2 :: [Int] -> Int
29 part2 = snd . head . dropWhile unRepeated . scanl merge (S.empty, 0) . cycle
30
31 merge :: (IntSet, Int) -> Int -> (IntSet, Int)
32 merge (frequencies, frequency) change = (S.insert frequency frequencies, frequency + change)
33
34 unRepeated :: (IntSet, Int) -> Bool
35 unRepeated (frequencies, frequency) = frequency `S.notMember` frequencies
36
37 -- Parse the input file
38 type Parser = Parsec Void Text
39
40 sc :: Parser ()
41 sc = L.space (skipSome spaceChar) CA.empty CA.empty
42 -- sc = L.space (skipSome (char ' ')) CA.empty CA.empty
43
44
45 lexeme = L.lexeme sc
46 integer = lexeme L.decimal
47 signedInteger = L.signed sc integer
48
49 changesP = many signedInteger
50
51 successfulParse :: Text -> [Int]
52 successfulParse input =
53 case parse changesP "input" input of
54 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
55 Right changes -> changes