1 module Main(main) where
3 import Data.Array.IArray
5 -- Row 1 is top, column 1 is left
6 type Position = (Int, Int)
7 type Keyboard = Array Position Char
25 mkKeyboard :: [String] -> Keyboard
26 mkKeyboard kb = array ((0, 0), (length kb - 1, length (kb!!0) - 1))
27 [((i, j), c) | (i, r) <- enumerate kb, (j, c) <- enumerate r]
29 keyboard1 = mkKeyboard kb1
30 keyboard2 = mkKeyboard kb2
32 findKey :: Keyboard -> Char-> Position
33 findKey kb c = fst $ head $ filter (\a -> (snd a) == c) $ assocs kb
35 -- data Coord = One | Two | Three
36 -- deriving (Read, Show, Eq, Ord, Enum, Bounded)
37 -- -- instance Bounded Coord where
38 -- -- minBound = Coord 1
39 -- -- maxBound = Coord 3
41 -- data Position = Position Coord Coord
42 -- deriving (Show, Eq)
46 instrText <- readFile "data/advent02.txt"
47 let instructions = lines instrText
51 part1 :: [String] -> IO ()
52 part1 instructions = do
53 putStrLn $ followInstructions keyboard1 instructions
56 part2 :: [String] -> IO ()
57 part2 instructions = do
58 putStrLn $ followInstructions keyboard2 instructions
61 followInstructions :: Keyboard -> [String] -> String
62 followInstructions kb instr = moveSeries kb (startPosition kb) instr
65 startPosition :: Keyboard -> Position
66 startPosition kb = findKey kb '5'
68 moveSeries :: Keyboard -> Position -> [String] -> String
69 moveSeries _ _ [] = []
70 moveSeries kb p (i:is) = (n:ns)
71 where p' = makeMoves kb p i
73 ns = moveSeries kb p' is
75 makeMoves :: Keyboard -> Position -> [Char] -> Position
76 makeMoves kb p ms = foldl (safeMove kb) p ms
78 safeMove :: Keyboard -> Position -> Char -> Position
79 safeMove kb pos dir = maybeRevert kb pos (move pos dir)
81 move :: Position -> Char -> Position
82 move (r, c) 'U' = (r-1, c)
83 move (r, c) 'D' = (r+1, c)
84 move (r, c) 'L' = (r, c-1)
85 move (r, c) 'R' = (r, c+1)
87 maybeRevert :: Keyboard -> Position -> Position -> Position
88 maybeRevert kb oldPos newPos
89 | kb ! newPos == 'x' = oldPos