Advent of Code solutions
at main 48 lines 1.2 kB view raw
1data Instruction 2 = N Int 3 | E Int 4 | S Int 5 | W Int 6 | R Int 7 | L Int 8 | F Int 9 deriving (Show, Eq) 10 11l :: Pos -> Pos 12l (x, y) = (-y, x) 13 14r :: Pos -> Pos 15r (x, y) = (y, -x) 16 17parse :: String -> Instruction 18parse ('N' : rest) = N (read rest) 19parse ('E' : rest) = E (read rest) 20parse ('S' : rest) = S (read rest) 21parse ('W' : rest) = W (read rest) 22parse ('R' : rest) = R (read rest `div` 90) 23parse ('L' : rest) = L (read rest `div` 90) 24parse ('F' : rest) = F (read rest) 25parse _ = error "Invalid instruction" 26 27type Pos = (Int, Int) 28 29run :: [Instruction] -> (Pos, Pos) -> (Pos, Pos) 30run [] = id 31run (i : is) = run is . apply i 32 33apply :: Instruction -> (Pos, Pos) -> (Pos, Pos) 34apply (N n) ((x, y), p) = ((x, y + n), p) 35apply (S n) ((x, y), p) = ((x, y - n), p) 36apply (E n) ((x, y), p) = ((x + n, y), p) 37apply (W n) ((x, y), p) = ((x - n, y), p) 38apply (L 0) h = h 39apply (L n) (w, p) = apply (L $ n - 1) (l w, p) 40apply (R 0) h = h 41apply (R n) (w, p) = apply (R $ n - 1) (r w, p) 42apply (F n) ((dx, dy), (x, y)) = ((dx, dy), (x + dx * n, y + dy * n)) 43 44main :: IO () 45main = do 46 instructions <- fmap parse . lines <$> getContents 47 let (_, (x, y)) = run instructions ((10, 1), (0, 0)) in 48 print $ abs x + abs y