3 import Data.Text (Text)
4 -- import qualified Data.Text as T
5 import qualified Data.Text.IO as TIO
7 import Data.Attoparsec.Text hiding (take)
8 -- import Data.Attoparsec.Combinator
9 -- import Control.Applicative
10 -- import Control.Applicative.Combinators
12 import qualified Data.Set as S
13 import Linear (V2(..), (^+^))
14 -- import Data.Semigroup
18 data Direction = NE | E | SE | SW | W | NW
19 deriving (Show, Eq, Enum, Bounded)
21 type Tile = V2 Int -- x, y
22 type Grid = S.Set Tile
24 instance Semigroup Int where
27 instance Monoid Int where
32 do text <- TIO.readFile "data/advent24.txt"
33 let walks = successfulParse text
34 let grid0 = foldr flipTile S.empty walks
38 part1 grid0 = S.size grid0
39 part2 grid0 = S.size $ (iterate update grid0) !! 100
41 delta :: Direction -> Tile
50 flipTile :: Tile -> Grid -> Grid
52 | tile `S.member` tiles = S.delete tile tiles
53 | otherwise = S.insert tile tiles
56 neighbourSpaces :: Tile -> Grid
57 neighbourSpaces here = S.fromList $ map nbrSpace [minBound .. maxBound] -- [NE .. NW]
58 where nbrSpace d = here ^+^ (delta d)
60 countOccupiedNeighbours :: Tile -> Grid -> Int
61 countOccupiedNeighbours cell grid =
62 S.size $ S.intersection grid $ neighbourSpaces cell
64 tileBecomesWhite :: Grid -> Tile -> Bool
65 tileBecomesWhite grid cell = black && ((nNbrs == 0) || (nNbrs > 2))
66 where black = cell `S.member` grid
67 nNbrs = countOccupiedNeighbours cell grid
69 tileBecomesBlack :: Grid -> Tile -> Bool
70 tileBecomesBlack grid cell = white && (nNbrs == 2)
71 where white = cell `S.notMember` grid
72 nNbrs = countOccupiedNeighbours cell grid
74 update :: Grid -> Grid
75 update grid = (grid `S.union` newBlacks) `S.difference` newWhites
76 where neighbours = (S.foldr mergeNeighbours S.empty grid) `S.difference` grid
77 mergeNeighbours cell acc = S.union acc $ neighbourSpaces cell
78 newWhites = S.filter (tileBecomesWhite grid) grid
79 newBlacks = S.filter (tileBecomesBlack grid) neighbours
82 -- Parse the input file
84 tilesP = tileP `sepBy` endOfLine
85 tileP = foldMap delta <$> many1 stepP
87 stepP = choice [neP, nwP, seP, swP, eP, wP]
96 -- successfulParse :: Text -> [Tile]
97 successfulParse input =
98 case parseOnly tilesP input of
99 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err