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
42 instruction_text <- TIO.readFile "data/01-mowmaster.txt"
43 let instructions = successfulParse instruction_text
44 print $ part1 instructions
45 print $ part2 instructions
47 part1 :: [Instruction] -> Int
50 part2 :: [Instruction] -> Int
51 part2 instructions = finalDistance $ executeAll instructions
52 where executeAll = foldl' execute initialMowmaster
54 initialMowmaster = Mowmaster North (0, 0)
57 -- Calculate manhattan distance from start to this state
58 finalDistance :: Mowmaster -> Int
59 finalDistance m = (abs e) + (abs n)
60 where (e, n) = position m
64 execute :: Mowmaster -> Instruction -> Mowmaster
65 execute m (Forward s) = m {position = forward s (direction m) (position m)}
66 execute m Clockwise = m {direction = turnCW (direction m)}
67 execute m Anticlockwise = m {direction = turnACW (direction m)}
70 -- Move in the current direction
71 forward :: Int -> Direction -> Position -> Position
72 forward s North (e, n) = (e, n+s)
73 forward s South (e, n) = (e, n-s)
74 forward s West (e, n) = (e-s, n)
75 forward s East (e, n) = (e+s, n)
78 -- | a `succ` that wraps
79 turnCW :: (Bounded a, Enum a, Eq a) => a -> a
80 turnCW dir | dir == maxBound = minBound
81 | otherwise = succ dir
83 -- | a `pred` that wraps
84 turnACW :: (Bounded a, Enum a, Eq a) => a -> a
85 turnACW dir | dir == minBound = maxBound
86 | otherwise = pred dir
89 -- Parse the input file
91 type Parser = Parsec Void Text
93 -- treat comment lines as whitespace
95 sc = L.space space1 lineComment CA.empty
96 where lineComment = L.skipLineComment "#"
99 integer = lexeme L.decimal
102 -- instructions is some optional space followed by many instructions
103 instrsP = optional sc *> many instrP
105 -- an instruction is either F, C, or A
106 instrP = forwardP <|> cwP <|> acwP
108 -- parse each instruction
109 forwardP = Forward <$> (symb "F" *> integer)
110 cwP = Clockwise <$ symb "C"
111 acwP = Anticlockwise <$ symb "A"
113 successfulParse :: Text -> [Instruction]
114 successfulParse input =
115 case parse instrsP "input" input of
116 Left _error -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
117 Right instrs -> instrs