From 9e245fe007355f726f3af5ecf843f1a051e72fb3 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Sat, 14 Dec 2024 10:28:43 -0500 Subject: [PATCH] Print the final position for reference --- hs/src/Day14.hs | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/hs/src/Day14.hs b/hs/src/Day14.hs index 1037de22..f80eac39 100644 --- a/hs/src/Day14.hs +++ b/hs/src/Day14.hs @@ -7,6 +7,7 @@ module Day14 (part1, part1', part2) where import Common (groupConsecutiveBy) import Control.Monad (join, liftM2) +import Data.Char (intToDigit) import Data.Map qualified as Map (findWithDefault) import Data.Map.Strict qualified as Map (fromListWith) import Data.Ord (Down (Down)) @@ -14,6 +15,7 @@ import Data.Set qualified as Set (fromList, toList) import Data.String (IsString) import Data.Text (Text) import Data.Void (Void) +import Debug.Trace (traceM) import Text.Megaparsec (MonadParsec, ParseErrorBundle, Stream (Token, Tokens), parse, sepEndBy1) import Text.Megaparsec.Char (char, newline, string) import Text.Megaparsec.Char.Lexer qualified as L (decimal, signed) @@ -44,16 +46,30 @@ part1' width height input = do part2 :: Text -> Either (ParseErrorBundle Text Void) Int part2 input = do robots <- parse parser "" input - pure . snd . minimum $ - [ (Down $ maximum $ map length verticalLines, t) - | t <- [0 .. lcm width height - 1], - let verticalLines = - groupConsecutiveBy isLine . Set.toList . Set.fromList $ - [ ((y0 + vy * t) `mod` height, (x0 + vx * t) `mod` width) - | ((x0, y0), (vx, vy)) <- robots - ] - isLine (y0, x0) (y1, x1) = y0 == y1 && x0 + 1 == x1 - ] + let (_, bestTime) = + minimum + [ (Down $ maximum $ map length verticalLines, t) + | t <- [0 .. lcm width height - 1], + let verticalLines = + groupConsecutiveBy isLine . Set.toList . Set.fromList $ + [ ((y0 + vy * t) `mod` height, (x0 + vx * t) `mod` width) + | ((x0, y0), (vx, vy)) <- robots + ] + isLine (y0, x0) (y1, x1) = y0 == y1 && x0 + 1 == x1 + ] + positions = + Map.fromListWith (+) $ + [ (((x0 + vx * bestTime) `mod` width, (y0 + vy * bestTime) `mod` height), 1) + | ((x0, y0), (vx, vy)) <- robots + ] + line y = + [ case Map.findWithDefault 0 (x, y) positions of + 0 -> '.' + n -> if n < 10 then intToDigit n else '+' + | x <- [0 .. width - 1] + ] + mapM_ (traceM . line) [0 .. height - 1] + pure bestTime where width = 101 height = 103