This commit is contained in:
Jens Kadenbach
2022-12-12 09:57:32 +01:00
parent 08306ed57d
commit 17e4d9d0ab
5 changed files with 415 additions and 1 deletions

79
src/Day10.hs Normal file
View File

@@ -0,0 +1,79 @@
module Day10
( Instruction (..),
parseProgram,
signalStrength,
executeProgram,
draw,
isSpriteDrawn,
day10
)
where
import Control.Arrow ((>>>))
import qualified Data.Matrix as M
import Debug.Trace (trace)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
data Instruction = Addx Int | Noop
deriving (Show, Eq)
newtype Pixel = Pixel Bool deriving (Eq)
instance Show Pixel where
show (Pixel True) = ""
show (Pixel False) = ""
type CRT = String
parseProgram :: String -> [Instruction]
parseProgram = lines >>> map parseProgram'
where
parseProgram' :: String -> Instruction
parseProgram' "noop" = Noop
parseProgram' line = splitAt 4 >>> snd >>> read >>> Addx $ line
isSpriteDrawn :: Int -> Int -> Bool
isSpriteDrawn x p = abs (position - x) <= 1
where
position = p `mod` 40
draw :: [Int] -> CRT
draw registerValues = unlines lastPicture
where
pictures = zipWith isSpriteDrawn registerValues [0..]
lastPicture = concatMap (show . Pixel) >>> chunksOf 40 $ pictures
signalStrength :: [Int] -> Int
signalStrength e = start + sum computedRest
where
start = e !! 20 * 20
rest = drop 20 e
withCycle = zip [60, 100..] (every 40 rest)
computedRest = [c*r | (c,r) <- withCycle]
every :: Int -> [a] -> [a]
every n xs = case drop (n-1) xs of
y : ys -> y : every n ys
[] -> []
executeProgram :: [Instruction] -> [Int]
executeProgram = scanl (+) 1 . concatMap execOne
where
execOne instruction = case instruction of
Noop -> [0]
Addx x -> [0, x]
day10 :: IO ()
day10 = do
input <- readFile "ressources/day10-input"
putStrLn "Day10"
let states = parseProgram >>> executeProgram $ input
let signal = signalStrength states
let crt = draw states
putStrLn ("Signal strength: " ++ show signal)
putStrLn ("CRT picture: \n" ++ crt)

View File

@@ -11,9 +11,10 @@ import Day6 (day6)
import Day7 (day7)
import Day8 (day8)
import Day9 (day9)
import Day10 (day10)
days :: [IO ()]
days = [day1, day2, day3, day4, day5, day6, day7, day8, day9]
days = [day1, day2, day3, day4, day5, day6, day7, day8, day9, day10]
sep :: IO ()
sep = putStrLn "---------"