Created
February 8, 2024 19:10
-
-
Save kamoshi/9d9a62fc62398e261c54853a36473ffc to your computer and use it in GitHub Desktop.
Advent of Code 2023 04, but it's pointfree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE TupleSections #-} | |
module Day04 (parse, solveA, solveB) where | |
import Data.Void (Void) | |
import Data.Text (Text) | |
import Data.Bits (shiftL, shiftR) | |
import Data.Bifunctor (first) | |
import Text.Megaparsec (Parsec, many, eof, runParser, errorBundlePretty) | |
import Text.Megaparsec.Char (string, space, char) | |
import Text.Megaparsec.Char.Lexer (decimal) | |
import Control.Monad (ap) | |
type Card = (Int, ([Int], [Int])) | |
type Parser = Parsec Void Text | |
parseCards :: Parser [Card] | |
parseCards = many ((,) <$> (string "Card" *> space *> decimal) <*> ((,) <$> (char ':' *> space *> many (decimal <* space)) <*> (char '|' *> space *> many (decimal <* space)))) <* eof | |
parse :: Text -> Either String [Card] | |
parse = first errorBundlePretty . runParser parseCards "" | |
intersect :: [Int] -> [Int] -> [Int] | |
intersect = filter . flip elem | |
matching :: Card -> [Int] | |
matching = uncurry intersect . snd | |
toScore :: [Int] -> Int | |
toScore = (`shiftR` 1) . (1 `shiftL`) . length | |
solveA :: [Card] -> Int | |
solveA = sum . map (toScore . matching) | |
copies :: Card -> [Int] | |
copies = ap (map . (+) . fst) (enumFromTo 1 . length . matching) | |
nextState :: [Card] -> ([Int], [Card]) -> ([Int], [Card]) | |
nextState = (`ap` snd) . (. fst) . flip (ap . ((,) .) . flip ((<>) . map fst)) . (. (copies =<<)) . map . (. pred) . (!!) | |
solveB :: [Card] -> Int | |
solveB = ap (((length . fst . head . filter (null . snd)) .) . iterate . nextState) ([],) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment