-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay24.hs
More file actions
94 lines (82 loc) · 2.71 KB
/
Day24.hs
File metadata and controls
94 lines (82 loc) · 2.71 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
module Day24
( part1
, part2
) where
import Control.Monad (void)
import Data.Either (fromRight)
import Data.HashSet as St (HashSet, delete, difference, empty,
filter, fromList, insert,
intersection, map, member, size,
union)
import Data.List as L (map)
import Data.Maybe (fromJust, isNothing)
import Helpers.Graph (Pos)
import Helpers.Parsers (Parser)
import Linear.V2 (V2 (..))
import Text.Megaparsec (count, eof, parse, try, (<|>))
import Text.Megaparsec.Char (char, letterChar, string)
type Floor = HashSet Pos
directions =
[ ("e", V2 2 0)
, ("w", V2 (-2) 0)
, ("ne", V2 1 (-1))
, ("se", V2 1 1)
, ("nw", V2 (-1) (-1))
, ("sw", V2 (-1) 1)
]
neighbSeed = fromList . L.map snd $ directions
parseFloor :: Floor -> String -> Floor
parseFloor floor = fromRight empty . parse (parseTile floor) ""
parseTile :: Floor -> Parser Floor
parseTile floor = do
r <- parseDir
let result
| r `member` floor = delete r floor
| otherwise = insert r floor
return result
parseDir :: Parser Pos
parseDir = try e <|> try w <|> try two <|> end
where
e = do
void . char $ 'e'
r <- parseDir
return (V2 2 0 + r)
w = do
void . char $ 'w'
r <- parseDir
return (V2 (-2) 0 + r)
two = do
key <- count 2 letterChar
let d = fromJust . lookup key $ directions
r <- parseDir
return (d + r)
end = do
eof
return (V2 0 0)
tile :: Pos -> Floor -> String -> Floor
tile pos floor s
| null s = nFloor
| otherwise = tile nPos floor rest
where
(cur, rest)
| head s == 'e' || head s == 'w' = splitAt 1 s
| otherwise = splitAt 2 s
nPos = (+ pos) . fromJust . lookup cur $ directions
nFloor
| member pos floor = delete pos floor
| otherwise = insert pos floor
gol :: Floor -> Floor
gol floor = stillAlive `union` reborn
where
stillAlive = St.filter ((`elem` [1, 2]) . size . livingNeighbours) floor
allNeighbours = foldl union empty . St.map neighbours $ floor
notAlive = difference allNeighbours floor
reborn = St.filter ((== 2) . size . livingNeighbours) notAlive
livingNeighbours = intersection floor . neighbours
neighbours x = St.map (x +) neighbSeed
tileFloor :: String -> Floor
tileFloor = foldl parseFloor empty . lines
part1 :: Bool -> String -> String
part1 _ = show . size . tileFloor
part2 :: Bool -> String -> String
part2 _ = show . size . last . take 101 . iterate gol . tileFloor