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)
50 isFinished :: Maze -> Progress -> Bool
51 isFinished maze progress = isSpace $ location maze (row progress) (column progress)
53 location :: Maze -> Int -> Int -> Char
54 location maze r c = (maze!!r)!!c
57 navigate :: Maze -> Progress
58 navigate maze = navigate' maze progress
59 where progress = startProgress maze
61 navigate' :: Maze -> Progress -> Progress
62 navigate' maze progress =
63 if isFinished maze progress
65 else navigate' maze (step maze progress)
68 step :: Maze -> Progress -> Progress
69 step maze progress = progress {row = r', column = c', direction = d', letters = l', stepCount = sc'}
70 where r = row progress
72 thisChar = location maze r c
73 l' = if isAlpha thisChar then (letters progress) ++ [thisChar] else letters progress
74 d' = if isJunction thisChar then newDirection maze progress else direction progress
78 sc' = stepCount progress + 1
80 newDirection :: Maze -> Progress -> Direction
81 newDirection maze progress =
82 if d == Up || d == Down
83 then if isSpace leftChar then Right else Left
84 else if isSpace upChar then Down else Up
85 where d = direction progress
88 upChar = location maze (r - 1) c
89 leftChar = location maze r (c - 1)