|
@@ -19,7 +19,8 @@ module Day9
|
19
|
19
|
where
|
20
|
20
|
|
21
|
21
|
import Control.Arrow ((>>>))
|
22
|
|
-import Data.List (nub)
|
|
22
|
+import Control.Monad.Trans.State.Strict (State, runState, modify)
|
|
23
|
+import qualified Data.Set as S
|
23
|
24
|
|
24
|
25
|
newtype Move = Move (Int, Int)
|
25
|
26
|
deriving (Show, Eq)
|
|
@@ -49,17 +50,26 @@ type Pos = (Int, Int)
|
49
|
50
|
|
50
|
51
|
data Grid = Grid {h :: Pos, t :: Pos} deriving (Show, Eq)
|
51
|
52
|
|
52
|
|
-recordPositions :: [Step] -> [Pos]
|
53
|
|
-recordPositions steps = nub (lastTailPos:positions)
|
|
53
|
+data MovementLog = MovementLog { visited :: S.Set Pos, recordedSteps :: [Step] }
|
|
54
|
+ deriving (Show, Eq)
|
|
55
|
+
|
|
56
|
+appendOne :: (Pos, Step) -> MovementLog -> MovementLog
|
|
57
|
+appendOne (p, s) (MovementLog v steps) =
|
|
58
|
+ MovementLog (S.insert p v) (s:steps)
|
|
59
|
+
|
|
60
|
+recordPositions :: [Step] -> ([Pos], [Step])
|
|
61
|
+recordPositions steps = (allPositions, allSteps)
|
54
|
62
|
where
|
55
|
|
- (positions, _, Grid { t = lastTailPos}) = recordPositions' [] steps startGrid
|
56
|
|
- recordPositions' :: [Pos] -> [Step] -> Grid -> ([Pos], [Step], Grid)
|
57
|
|
- recordPositions' pos [] grid = (pos, [], grid)
|
58
|
|
- recordPositions' pos (m : ms) Grid {h = headPos, t = tailPos} =
|
|
63
|
+ allPositions = S.toList $ S.insert lastTailPos (visited state)
|
|
64
|
+ allSteps = reverse (recordedSteps state)
|
|
65
|
+ ((_, Grid { t = lastTailPos}), state) = runState (recordPositions' steps startGrid) (MovementLog S.empty [])
|
|
66
|
+ recordPositions' :: [Step] -> Grid -> State MovementLog ([Step], Grid)
|
|
67
|
+ recordPositions' [] grid = return ([], grid)
|
|
68
|
+ recordPositions' (m : ms) Grid {h = headPos, t = tailPos} =
|
59
|
69
|
let newHead = headPos `step` m
|
60
|
70
|
followStep = follow newHead tailPos
|
61
|
71
|
newTail = tailPos `step` followStep
|
62
|
|
- in recordPositions' (tailPos : pos) ms Grid {h = newHead, t = newTail}
|
|
72
|
+ in modify (appendOne (newTail, followStep)) >> recordPositions' ms Grid {h = newHead, t = newTail}
|
63
|
73
|
|
64
|
74
|
startGrid :: Grid
|
65
|
75
|
startGrid = Grid {h = p, t = p}
|
|
@@ -106,5 +116,5 @@ day9 = do
|
106
|
116
|
input <- readFile "ressources/day09-input"
|
107
|
117
|
putStrLn "Day9"
|
108
|
118
|
let movements = parseMovements input
|
109
|
|
- let positions = concatMap normalizeMovement >>> recordPositions >>> length $ movements
|
|
119
|
+ let positions = concatMap normalizeMovement >>> recordPositions >>> fst >>> length $ movements
|
110
|
120
|
putStrLn ("Number of distinct positions " ++ show positions)
|