Finally done day 24
[advent-of-code-19.git] / advent01 / src / advent01.hs
1 import Data.Text (Text)
2 import qualified Data.Text.IO as TIO
3
4 import Data.Void (Void)
5
6 import Text.Megaparsec
7 import Text.Megaparsec.Char
8 import qualified Text.Megaparsec.Char.Lexer as L
9 import qualified Control.Applicative as CA
10
11
12 main :: IO ()
13 main = do
14 text <- TIO.readFile "data/advent01.txt"
15 let changes = successfulParse text
16 print $ part1 changes
17 print $ part2 changes
18
19
20 part1 :: [Int] -> Int
21 part1 = sum . map fuelRequired
22
23 part2 :: [Int] -> Int
24 part2 = sum . map fuelForFuel
25
26
27 fuelRequired :: Int -> Int
28 fuelRequired m = (m `div` 3) - 2
29
30 fuelForFuel :: Int -> Int
31 fuelForFuel = sum . takeWhile (> 0) . drop 1 . iterate fuelRequired
32
33
34 -- Parse the input file
35 type Parser = Parsec Void Text
36
37 sc :: Parser ()
38 sc = L.space (skipSome spaceChar) CA.empty CA.empty
39 -- sc = L.space (skipSome (char ' ')) CA.empty CA.empty
40
41
42 lexeme = L.lexeme sc
43 integer = lexeme L.decimal
44 -- signedInteger = L.signed sc integer
45
46 moduleP = many integer
47
48 successfulParse :: Text -> [Int]
49 successfulParse input =
50 case parse moduleP "input" input of
51 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
52 Right changes -> changes