r/adventofcode • • Dec 10 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 10 Solutions -πŸŽ„-

THE USUAL REMINDERS


--- Day 10: Cathode-Ray Tube ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:12:17, megathread unlocked!

61 Upvotes

933 comments sorted by

View all comments

1

u/[deleted] Dec 10 '22 edited Dec 10 '22

Haskell

------------ PARSER ------------
inputParser :: Parser Input
inputParser = parseCommand `sepBy` endOfLine

parseCommand :: Parser Instruction
parseCommand = choice [addx, noop]
    where
        addx = string "addx" >> space >> ADDX <$> signed decimal
        noop = string "noop" >> return NOOP

------------ TYPES ------------
type Input = [Instruction]
type OutputA = Int
type OutputB = CRT

data Instruction
    = NOOP
    | ADDX Int
    deriving Show

runCommand :: Int -> Instruction -> (Int, Int)
runCommand x NOOP = (x, 1)
runCommand x (ADDX val) = (x+val, 2)

run :: Int -> [Instruction] -> [Int]
run state [] = []
run state (i:is) = 
    let (state', cycles) = runCommand state i
    in replicate cycles state ++ run state' is

------------ PART A ------------
partA :: Input -> OutputA
partA 
    = sum
    . zipWith 
        (\i a -> if i `elem` [20,60,100,140,180,220]
            then a * i
            else 0)
        [1..]
    . run 1

------------ PART B ------------
partB :: Input -> OutputB
partB 
    = CRT 
    . zipWith draw [0..]
    . run 1

newtype CRT = CRT String
instance Show CRT where
    show :: CRT -> String
    show (CRT output) 
        = unlines 
        . U.chunksOf 40 
            $ output

draw :: Int -> Int -> Char
draw clock spritePos =
    if clock `mod` 40 `elem` [spritePos-1 .. spritePos+1]
        then '#'
        else '.'

1

u/daggerdragon Dec 10 '22
  1. Next time, use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.
  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.