--- Writeup at https://work.njae.me.uk/2023/12/15/advent-of-code-2023-day-13/
+-- Writeup at https://work.njae.me.uk/2023/12/18/advent-of-code-2023-day-14/
import AoC
import Data.List
do dataFileName <- getDataFileName
text <- readFile dataFileName
let grid = transpose $ fmap (fmap readElem) $ lines text
- -- print grid
- -- print $ rollGrid $ transpose grid
- -- let r1 = rollToCompletion grid
- -- print r1
- -- putStrLn $ showGrid r1
- -- print $ transpose $ fmap reverse r1
+ -- print $ showGrid grid
print $ part1 grid
- -- print $ rollCycle grid
- -- putStrLn $ showGrid $ rollCycle grid
- -- putStrLn $ showGrid $ rollCycle $ rollCycle grid
- -- putStrLn $ showGrid $ rollCycle $ rollCycle $ rollCycle grid
- -- print $ findRepeat grid
-
-
-
print $ part2 grid
- -- print $ part2 patts
-part1 :: Grid -> Int
+part1, part2 :: Grid -> Int
part1 grid = scoreGrid grid'
where grid' = rollToCompletion grid
part2 grid = scoreGrid finalGrid
- where (grid', cache, i) = findRepeat grid
+ where (grid', cache, repeatEnd) = findRepeat grid
repeatStart = cache M.! grid'
- repeatLen = i - repeatStart
- finalIndex = (1e9 - repeatStart - 1) `mod` repeatLen
+ repeatLen = repeatEnd - repeatStart
+ finalIndex = ((1e9 - repeatStart) `mod` repeatLen) + repeatStart
(finalGrid, _) = M.findMin $ M.filter (== finalIndex) cache
readElem :: Char -> Element
rollCycle :: Grid -> Grid
rollCycle = appEndo (stimes 4 (Endo rotate1 <> Endo rollToCompletion))
+findRepeat :: Grid -> (Grid, Cache, Int)
+findRepeat grid = head $ dropWhile test $ iterate go (grid, M.empty, 0)
+ where test (g, c, _) = g `M.notMember` c
+ go (g, c, i) = (rollCycle g, M.insert g i c, (i + 1))
+
showGrid :: Grid -> String
showGrid grid = unlines $ fmap (fmap showElem) $ transpose grid
where showElem Empty = '.'
showElem Cube = '#'
showElem Round = 'O'
-
-
-rollCycleWithCache (grid, cache, index) = (rollCycle grid, M.insert grid index cache, (index + 1))
-
-findRepeat grid = head $ dropWhile test $ iterate rollCycleWithCache (grid, M.empty, 0)
- where test (g, c, i) = g `M.notMember` c
-