From ac45449f8882a76612dcca699f84f54f08edcff4 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Wed, 16 Dec 2020 18:45:47 +0100 Subject: Day 12 --- 2020/12.hs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/2020/12.hs b/2020/12.hs index 92ce67c..cb1b1f1 100644 --- a/2020/12.hs +++ b/2020/12.hs @@ -72,7 +72,37 @@ sail (Sail offset dirm posm) (State pos dir) = manhattan :: Num a => V2 a -> a manhattan (V2 a b) = abs a + abs b +------------ +-- PART 2 -- +------------ + +data State2 = State2 { sPos2 :: V2 Int, sWP :: V2 Int } + deriving (Show) + +runInstr2 :: String -> State2 -> State2 +runInstr2 (c : ns) = case (c, read ns :: Int) of + ('N', n) -> addWP (V2 0 n) + ('S', n) -> addWP (V2 0 (-n)) + ('E', n) -> addWP (V2 n 0) + ('W', n) -> addWP (V2 (-n) 0) + ('F', n) -> \(State2 ship wp) -> State2 (ship !+! (wp *$ n)) wp + ('R', 90) -> mulWP rotRightMat + ('R', 180) -> mulWP mirrorMat + ('R', 270) -> mulWP rotLeftMat + ('L', 90) -> mulWP rotLeftMat + ('L', 180) -> mulWP mirrorMat + ('L', 270) -> mulWP rotRightMat + _ -> error "Cannot parse instr" + where + rotRightMat = M2 0 1 (-1) 0 + rotLeftMat = rotRightMat *$ (-1) + mirrorMat = M2 (-1) 0 0 (-1) + addWP v (State2 ship wp) = State2 ship (wp !+! v) + mulWP m (State2 ship wp) = State2 ship (m *! wp) +runInstr2 _ = error "Cannot parse empty instr" + main :: IO () main = do - input <- map parseInstr <$> getInput 12 - print (manhattan . sPos $ foldl' (flip sail) (State (V2 0 0) (V2 1 0)) input) + input <- getInput 12 + print (manhattan . sPos $ foldl' (flip sail) (State (V2 0 0) (V2 1 0)) (map parseInstr input)) + print (manhattan . sPos2 $ foldl' (flip runInstr2) (State2 (V2 0 0) (V2 10 1)) input) -- cgit v1.2.3-54-g00ecf