1 import Data.Array.IArray
3 -- Row 1 is top, column 1 is left
4 type Position = (Int, Int)
5 type Keyboard = Array Position Char
23 mkKeyboard :: [String] -> Keyboard
24 mkKeyboard kb = array ((0, 0), (length kb - 1, length (kb!!0) - 1))
25 [((i, j), c) | (i, r) <- enumerate kb, (j, c) <- enumerate r]
27 keyboard1 = mkKeyboard kb1
28 keyboard2 = mkKeyboard kb2
30 findKey :: Keyboard -> Char-> Position
31 findKey kb c = fst $ head $ filter (\a -> (snd a) == c) $ assocs kb
33 -- data Coord = One | Two | Three
34 -- deriving (Read, Show, Eq, Ord, Enum, Bounded)
35 -- -- instance Bounded Coord where
36 -- -- minBound = Coord 1
37 -- -- maxBound = Coord 3
39 -- data Position = Position Coord Coord
40 -- deriving (Show, Eq)
44 instrText <- readFile "advent02.txt"
45 let instructions = lines instrText
49 part1 :: [String] -> IO ()
50 part1 instructions = do
51 print $ followInstructions keyboard1 instructions
54 part2 :: [String] -> IO ()
55 part2 instructions = do
56 print $ followInstructions keyboard2 instructions
59 followInstructions :: Keyboard -> [String] -> String
60 followInstructions kb instr = moveSeries kb (startPosition kb) instr
63 startPosition :: Keyboard -> Position
64 startPosition kb = findKey kb '5'
66 moveSeries :: Keyboard -> Position -> [String] -> String
67 moveSeries _ _ [] = []
68 moveSeries kb p (i:is) = (n:ns)
69 where p' = makeMoves kb p i
71 ns = moveSeries kb p' is
73 makeMoves :: Keyboard -> Position -> [Char] -> Position
74 makeMoves kb p ms = foldl (safeMove kb) p ms
76 safeMove :: Keyboard -> Position -> Char -> Position
77 safeMove kb pos dir = maybeRevert kb pos (move pos dir)
79 move :: Position -> Char -> Position
80 move (r, c) 'U' = (r-1, c)
81 move (r, c) 'D' = (r+1, c)
82 move (r, c) 'L' = (r, c-1)
83 move (r, c) 'R' = (r, c+1)
85 maybeRevert :: Keyboard -> Position -> Position -> Position
86 maybeRevert kb oldPos newPos
87 | kb ! newPos == 'x' = oldPos