Skip to content

Commit

Permalink
Print the final position for reference
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient committed Dec 14, 2024
1 parent 5ae3381 commit 9e245fe
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions hs/src/Day14.hs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ 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))
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)
Expand Down Expand Up @@ -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

0 comments on commit 9e245fe

Please sign in to comment.