Something went wrong. Try again.
advent of code solutions op.tngl.io
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677{-# LANGUAGE LambdaCase #-}
import Control.Monad (join)import Data.List (find, transpose)import Data.List.Split (splitOn)import Data.Maybe (isJust)import System.Environment (getArgs)import Text.Parsec.Charimport Text.ParserCombinators.Parsec
parseInt :: Parser IntparseInt = read <$> (spaces *> many1 digit)
parseNums :: Parser [Int]parseNums = parseInt `sepBy` char ','
parseBoardLine :: Parser [Int]parseBoardLine = parseInt `sepBy` many1 (char ' ')
type Board = [[Int]]
parseBoard :: Parser BoardparseBoard = parseBoardLine `sepBy` newline
parseInput :: Parser ([Int], [Board])parseInput = do nums <- parseNums <* newline boards <- parseBoard `sepBy` newline return (nums, boards)
doParse :: Parser a -> String -> adoParse parser input = v where Right v = parse parser "input" input
isVictor board = any row board || any row (transpose board) where row = all (== -1)
score :: Board -> Intscore = sum . concatMap (filter (> 0))
stepBoard call = map squish where squish = map (\x -> if x == call then -1 else x)
doRound boards call = map (stepBoard call) boards
doRound2 boards call = filter (not . isVictor) $ doRound boards call
victor :: Int -> [Board] -> Maybe Intvictor call boards = (* call) . score <$> find isVictor boards
ans1 boards calls = join $ find isJust $ map (uncurry victor) $ zip (0 : calls) (scanl doRound boards calls)
ans2 boards calls = head $ dropWhile (null . snd) $ reverse $ zip calls (scanl doRound2 boards calls)
main = do n <- fmap (splitOn "\n\n") $ getArgs >>= \case ["-"] -> getContents [file] -> readFile file let calls = doParse parseNums $ head n boards = map (filter (not . null) . doParse parseBoard) (tail n) print $ ans1 boards calls print $ (\(call, boards) -> (* call) $ score $ stepBoard call (head boards)) $ ans2 boards calls