Day 2
[advent-of-code-21.git] / advent02 / Main.hs
1 import Data.Text ()
2 import qualified Data.Text.IO as TIO
3
4 import Data.Attoparsec.Text
5 import Control.Applicative
6
7 type Course = [Command]
8 data Command = Forward Int
9 | Up Int
10 | Down Int
11 deriving (Eq, Show)
12
13 data Position = Position Int Int -- forward, depth
14 deriving (Eq, Show)
15
16 data AimedPosition = AimedPosition Int Int Int -- forward, depth, aim
17 deriving (Eq, Show)
18
19 main :: IO ()
20 main =
21 do text <- TIO.readFile "data/advent02.txt"
22 let course = successfulParse text
23 print $ part1 course
24 print $ part2 course
25
26 part1 :: Course -> Int
27 part1 course = finalH * finalD
28 where (Position finalH finalD) = followCourse course
29
30 part2 :: Course -> Int
31 part2 course = finalH * finalD
32 where (AimedPosition finalH finalD _) = followAimedCourse course
33
34 followCourse :: Course -> Position
35 followCourse = foldl courseStep (Position 0 0)
36
37 courseStep :: Position -> Command -> Position
38 courseStep (Position h d) (Forward n) = Position (h + n) d
39 courseStep (Position h d) (Up n) = Position h (d - n)
40 courseStep (Position h d) (Down n) = Position h (d + n)
41
42 followAimedCourse :: Course -> AimedPosition
43 followAimedCourse = foldl courseAimedStep (AimedPosition 0 0 0)
44
45 courseAimedStep :: AimedPosition -> Command -> AimedPosition
46 courseAimedStep (AimedPosition h d a) (Forward n) = AimedPosition (h + n) (d + a * n) a
47 courseAimedStep (AimedPosition h d a) (Up n) = AimedPosition h d (a - n)
48 courseAimedStep (AimedPosition h d a) (Down n) = AimedPosition h d (a + n)
49
50
51 -- Parse the input file
52
53 courseP = commandP `sepBy` endOfLine
54 commandP = forwardP <|> upP <|> downP
55
56 forwardP = Forward <$> ("forward " *> decimal)
57 upP = Up <$> ("up " *> decimal)
58 downP = Down <$> ("down " *> decimal)
59
60 -- successfulParse :: Text -> (Integer, [Maybe Integer])
61 successfulParse input =
62 case parseOnly courseP input of
63 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
64 Right course -> course