never executed always true always false
1 {-# LANGUAGE FlexibleContexts #-}
2
3 {-|
4 Module: Y2021.D02
5 Description: Advent of Code 2021 Day 02 Solutions.
6 License: MIT
7 Maintainer: @tylerjl
8
9 Solutions to the 2021 day 02 set of problems for <adventofcode.com>.
10 -}
11 module Y2021.D02 where
12
13 import Data.Text (Text)
14 import qualified Text.Parsec as P
15 import Text.Parsec.Text (Parser)
16 import Y2015.Util (regularParse', intParser')
17 import Control.Applicative ((<|>))
18 import qualified Data.Text as T
19
20 data Navigation
21 = Forward Int
22 | Down Int
23 | Up Int
24
25 navParser :: Parser [Navigation]
26 navParser = P.many (parseNav <* P.optional P.endOfLine)
27
28 parseNav :: Parser Navigation
29 parseNav = Forward <$> pInstr "forward"
30 <|> Down <$> pInstr "down"
31 <|> Up <$> pInstr "up"
32
33 pInstr :: String -> Parser Int
34 pInstr s = P.string s *> P.skipMany1 P.space *> intParser'
35
36 part2A :: Text -> Int
37 part2A (regularParse' navParser -> Right navs) = uncurry (*) $ go (0, 0) navs
38 where go (x, y) (Forward n:xs) = go (x + n, y) xs
39 go (x, y) (Down n:xs) = go (x, y + n) xs
40 go (x, y) (Up n:xs) = go (x, y - n) xs
41 go coords [] = coords
42 part2A (regularParse' navParser -> Left err) = error (show err)
43
44 part2B :: Text -> Int
45 part2B (regularParse' navParser -> Right navs) = (\(x, y, _) -> x * y) $ go (0, 0, 0) navs
46 where go (x, y, aim) (Forward n:xs) = go (x + n, y + (aim * n), aim) xs
47 go (x, y, aim) (Down n:xs) = go (x, y, aim + n) xs
48 go (x, y, aim) (Up n:xs) = go (x, y, aim - n) xs
49 go coords [] = coords
50 part2B (regularParse' navParser -> Left err) = error (show err)
51
52 d2sample :: Text
53 d2sample = T.unlines
54 [ "forward 5"
55 , "down 5"
56 , "forward 8"
57 , "up 3"
58 , "down 8"
59 , "forward 2"
60 ]