From a9af1ff8e08c473ece30ccdee9ff1a895126c0b2 Mon Sep 17 00:00:00 2001 From: Neil Smith Date: Mon, 18 Dec 2023 15:20:37 +0000 Subject: [PATCH] Finsihed day 14 --- advent14/Main.hs | 38 +++++++++++--------------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/advent14/Main.hs b/advent14/Main.hs index efd4db6..1d0e71e 100644 --- a/advent14/Main.hs +++ b/advent14/Main.hs @@ -1,4 +1,4 @@ --- 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 @@ -17,33 +17,19 @@ main = 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 @@ -78,15 +64,13 @@ rotate1 = transpose . fmap reverse 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 - -- 2.34.1