Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Created December 12, 2022 14:40
Show Gist options
  • Save skatenerd/4c9c173a89d17c12f073d08ce5beee42 to your computer and use it in GitHub Desktop.
Save skatenerd/4c9c173a89d17c12f073d08ce5beee42 to your computer and use it in GitHub Desktop.
DayTen.hs
{-# LANGUAGE OverloadedStrings #-}
module DayTen
( partOne
) where
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import qualified Data.Maybe as M
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.List.Extra as LE
import qualified Control.Monad as CM
data Instruction = Noop | Add Int deriving (Show, Eq)
makeHistory instructions = (flatten $ L.unfoldr go (instructions, 1))
where go ([], _) = Nothing
go ((Noop:rest), runningTotal) = Just ([runningTotal], (rest, runningTotal))
go (((Add n):rest), runningTotal) = Just ([runningTotal, runningTotal], (rest, runningTotal + n))
flatten lists = L.concatMap identity lists
identity x = x
testLines = map T.pack ["noop", "addx 3", "addx -5"]
parse lines = map parseLine lines
where parseLine "noop" = Noop
parseLine line = Add $ readText $ last $ T.split (== ' ') line
readText = read . T.unpack
partOne lines = sum $ map getStrength indices
where getStrength index = (history !! index) * index
history = 0:(makeHistory lines)
indices = [20,60,100,140,180,220]
screenWidth = 40
renderMegaLine spriteHistory = map renderCharAtCycle [0..((length spriteHistory) - 1)]
where renderCharAtCycle c = isClose (spritePositionAt c) $ mod c screenWidth
isClose a b = (abs (a - b)) <= 1
spritePositionAt c = spriteHistory !! c
render spriteHistory = map renderLine (LE.chunksOf screenWidth (renderMegaLine spriteHistory))
where renderLine line = map (\e -> if e then '#' else '.') line
partTwo path = do
inputLines <- getLines path
let linesToPrint = render $ makeHistory inputLines
CM.forM_ linesToPrint print
getLines :: String -> IO [Instruction]
getLines path =
do
input <- TI.readFile path
let inputLines = T.lines input
parsed = parse inputLines
return parsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment