1 {-# LANGUAGE NegativeLiterals #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE OverloadedStrings #-}
4 {-# LANGUAGE TypeFamilies #-}
6 import Prelude hiding (Left, Right)
12 data Direction = Up | Down | Left | Right deriving (Show, Eq)
14 data Progress = Progress { row :: Int
16 , direction :: Direction
22 -- Note: assumes the maze comes with a padding border of spaces
23 -- all around it. Makes the "next location" checking much easier!
27 text <- readFile "data/advent19.txt"
29 let progress = navigate maze
30 print $ letters progress
31 print $ stepCount progress
34 startProgress :: Maze -> Progress
35 startProgress maze = Progress { row = 0, column = startCol
37 , letters = "", stepCount = 0}
38 where topRow = maze!!0
39 startCol = head $ elemIndices '|' topRow
41 delta :: Direction -> (Int, Int)
47 isJunction :: Char -> Bool
51 isFinished :: Maze -> Progress -> Bool
52 isFinished maze progress = isSpace $ location maze (row progress) (column progress)
54 location :: Maze -> Int -> Int -> Char
55 location maze r c = (maze!!r)!!c
58 navigate :: Maze -> Progress
59 navigate maze = navigate' maze progress
60 where progress = startProgress maze
62 navigate' :: Maze -> Progress -> Progress
63 navigate' maze progress =
64 if isFinished maze progress
66 else navigate' maze (step maze progress)
69 step :: Maze -> Progress -> Progress
70 step maze progress = progress {row = r', column = c', direction = d', letters = l', stepCount = sc'}
71 where r = row progress
73 thisChar = location maze r c
74 l' = if isAlpha thisChar then (letters progress) ++ [thisChar] else letters progress
75 d' = if isJunction thisChar then newDirection maze progress else direction progress
79 sc' = stepCount progress + 1
81 newDirection :: Maze -> Progress -> Direction
82 newDirection maze progress =
83 if d == Up || d == Down
84 then if isSpace leftChar then Right else Left
85 else if isSpace upChar then Down else Up
86 where d = direction progress
89 upChar = location maze (r - 1) c
90 leftChar = location maze r (c - 1)