-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day9.hs
executable file
·34 lines (29 loc) · 1.05 KB
/
Day9.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env stack
{-
stack script
--resolver lts-20.2
--package containers
-}
import qualified Data.Set as Set
parse :: String -> [Char]
parse s = replicate (read . drop 2 $ s) (head s)
headPath :: [Char] -> [(Int, Int)]
headPath = reverse . fst . foldl update ([(0, 0)], (0, 0))
where
update (visited, (x, y)) 'R' = ((x+1, y):visited, (x+1, y))
update (visited, (x, y)) 'L' = ((x-1, y):visited, (x-1, y))
update (visited, (x, y)) 'U' = ((x, y+1):visited, (x, y+1))
update (visited, (x, y)) c = ((x, y-1):visited, (x, y-1))
tailVisited :: [(Int, Int)] -> [(Int, Int)]
tailVisited = reverse . foldl update []
where
update [] v = [v]
update pos@((x', y'):_) (x, y)
| abs (x-x') <= 1 && abs (y-y') <= 1 = pos
| otherwise = (x' + signum (x-x'), y' + signum (y-y')):pos
main :: IO ()
main = do
input <- readFile "data/09.txt"
let headMotion = headPath . concatMap parse . lines $ input
print . length . Set.fromList . tailVisited $ headMotion
print . length . Set.fromList . flip (!!) 9 . iterate tailVisited $ headMotion