Skip to content

Instantly share code, notes, and snippets.

@mchav
Created December 3, 2024 06:14
Show Gist options
  • Save mchav/1681ef692ca237398a9f32d7e613ea99 to your computer and use it in GitHub Desktop.
Save mchav/1681ef692ca237398a9f32d7e613ea99 to your computer and use it in GitHub Desktop.
AOC 2024 Day 3
module Day3 where
import Data.List ( isPrefixOf )
import Data.List.Split ( splitOn )
import Data.Char ( isDigit )
run :: IO ()
run = do
instructions <- readFile "./data/day3/input"
let tuples = parseInstructions instructions
print $ sum $ map (uncurry (*)) tuples
parseInstructions :: String -> [(Int, Int)]
parseInstructions [] = []
parseInstructions xs
-- Comment this guard out for part one
| "don't()" `isPrefixOf` xs = parseInstructions (dropUntil "do()" xs)
| startsWithValid xs = extractValid xs : parseInstructions (tail $ dropWhile (')' /=) xs)
| otherwise = parseInstructions (tail xs)
startsWithValid :: String -> Bool
startsWithValid xs = isPrefixOf "mul(" xs &&
all (all isDigit) (splitOn "," $ takeWhile (')' /=) $ drop (length "mul(") xs)
dropUntil :: String -> String -> String
dropUntil _ [] = []
dropUntil prefix xs
| prefix `isPrefixOf` xs = xs
| otherwise = dropUntil prefix (tail xs)
extractValid :: String -> (Int, Int)
extractValid xs = let
[x, y] = splitOn "," $ takeWhile (')' /=) $ drop (length "mul(") xs
in (read x, read y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment