Day 17, Part 2 (slow)

This commit is contained in:
daniele 2024-12-21 17:40:09 +01:00
parent 5390addcff
commit a42f7bbbe1
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514
2 changed files with 24 additions and 2 deletions

View File

@ -1,6 +1,7 @@
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}
module Day17 (day17_1) where
module Day17 (day17_1, day17_2) where
import Control.Monad.State
import Data.Bits
@ -115,6 +116,11 @@ runProgram = do
_ -> return ()
runProgram
checkIfCreatesCopy :: Computer -> Bool
checkIfCreatesCopy c =
let o = map read . filter (not . null) . splitOn "," . output $ execState runProgram c
in o == program c
day17_1 :: IO ()
day17_1 = do
contents <- lines <$> readFile "input/day17.txt"
@ -124,3 +130,15 @@ day17_1 = do
computer = Computer {registerA = fst . fromJust $ uncons registers, registerB = registers !! 1, registerC = registers !! 2, pointer = 0, program = prog, output = ""}
putStr "Day 17, Puzzle 1 solution: "
print . drop 1 . output $ execState runProgram computer
day17_2 :: IO ()
day17_2 = do
contents <- lines <$> readFile "input/day17.txt"
let [r, [p]] = splitOn [""] contents
registers = map (read . filter isDigit) r
prog = map (read . filter isDigit) $ splitOn "," p
computer = Computer {registerA = 0, registerB = registers !! 1, registerC = registers !! 2, pointer = 0, program = prog, output = ""}
regA = [805464 * 2 ^ 27 ..] -- Threshold derived empirically, a better threshold must be possible because this is very slow, but got the correct answer.
putStrLn $
"Day 17, Puzzle 2 solution: "
++ show (fst . fromJust . uncons $ dropWhile (\x -> not (checkIfCreatesCopy computer {registerA = x})) regA)

View File

@ -15,7 +15,7 @@ import Day12 (day12_1)
import Day13 (day13_1, day13_2)
import Day14 (day14_1, day14_2)
import Day15 (day15_1)
import Day17 (day17_1)
import Day17 (day17_1, day17_2)
import Day18 (day18_1, day18_2)
import Day19 (day19_1)
import System.Environment (getArgs)
@ -92,6 +92,10 @@ main = do
day14_2
"15" : "1" : _ -> day15_1
"17" : "1" : _ -> day17_1
"17" : "2" : _ -> day17_2
"17" : _ -> do
day17_1
day17_2
"18" : "1" : _ -> day18_1
"18" : "2" : _ -> day18_2
"18" : _ -> do