1 {-# LANGUAGE OverloadedStrings #-}
3 import Data.List (foldl') -- import the strict fold
5 import Data.Text (Text)
6 -- import qualified Data.Text as T
7 import qualified Data.Text.IO as TIO
9 import Data.Void (Void)
11 import Text.Megaparsec -- hiding (State)
12 import Text.Megaparsec.Char
13 import qualified Text.Megaparsec.Char.Lexer as L
14 import qualified Control.Applicative as CA
21 type Position = (Int, Int)
23 -- the directions. See below for functions for turning
24 data Direction = North | East | South | West
25 deriving (Enum, Show, Bounded, Eq)
27 -- The currenct state of a Mowmaster
28 data Mowmaster = Mowmaster { direction :: Direction
29 , position :: Position
32 -- one instruction for the mowmaster
33 data Instruction = Forward Distance
41 instruction_text <- TIO.readFile "data/01-mowmaster.txt"
42 let instructions = successfulParse instruction_text
43 print $ part1 instructions
44 print $ part2 instructions
46 part1 :: [Instruction] -> Int
49 part2 :: [Instruction] -> Int
50 part2 = finalDistance . executeAll
51 where executeAll = foldl' execute initialMowmaster
53 initialMowmaster = Mowmaster East (0, 0)
56 -- Calculate manhattan distance from start to this state
57 finalDistance :: Mowmaster -> Int
58 finalDistance m = (abs e) + (abs n)
59 where (e, n) = position m
63 execute :: Mowmaster -> Instruction -> Mowmaster
64 execute m (Forward s) = m {position = forward s (direction m) (position m)}
65 execute m Clockwise = m {direction = turnCW (direction m)}
66 execute m Anticlockwise = m {direction = turnACW (direction m)}
68 -- Move in the current direction
69 forward :: Distance -> Direction -> Position -> Position
70 forward s North (e, n) = (e, n+s)
71 forward s South (e, n) = (e, n-s)
72 forward s West (e, n) = (e-s, n)
73 forward s East (e, n) = (e+s, n)
76 -- | a `succ` that wraps
77 turnCW :: (Bounded a, Enum a, Eq a) => a -> a
78 turnCW dir | dir == maxBound = minBound
79 | otherwise = succ dir
81 -- | a `pred` that wraps
82 turnACW :: (Bounded a, Enum a, Eq a) => a -> a
83 turnACW dir | dir == minBound = maxBound
84 | otherwise = pred dir
87 -- Parse the input file
89 type Parser = Parsec Void Text
91 -- treat comment lines as whitespace
93 sc = L.space space1 lineComment CA.empty
94 where lineComment = L.skipLineComment "#"
97 integer = lexeme L.decimal
100 -- instructions is some optional space followed by many instructions
101 instrsP = optional sc *> many instrP
103 -- an instruction is either F, C, or A
104 instrP = forwardP <|> cwP <|> acwP
106 -- parse each instruction
107 forwardP = Forward <$> (symb "F" *> integer)
108 cwP = Clockwise <$ symb "C"
109 acwP = Anticlockwise <$ symb "A"
111 successfulParse :: Text -> [Instruction]
112 successfulParse input =
113 case parse instrsP "input" input of
114 Left _error -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
115 Right instrs -> instrs