From 1552251e0ecf7915f682464eb3e71974ec41633d Mon Sep 17 00:00:00 2001 From: tzlil Date: Sat, 2 Dec 2023 13:57:02 +0200 Subject: solved day2 --- 2/1.hs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 2/1.hs (limited to '2/1.hs') diff --git a/2/1.hs b/2/1.hs new file mode 100644 index 0000000..9151408 --- /dev/null +++ b/2/1.hs @@ -0,0 +1,36 @@ +import Text.Parsec.String (Parser) +import Text.Parsec +import System.Environment +import Data.List +import Data.Function +import Data.Maybe +import qualified Data.Map as M +import Control.Monad + +data Color = Red | Green | Blue deriving (Eq,Ord) +type Handful = (Color, Int) +type Set = M.Map Color Int +type Game = (Int, [Set]) + +red = try $ string "red" *> pure Red +green = try $ string "green" *> pure Green +blue = try $ string "blue" *> pure Blue + +color :: Parser Color +color = red <|> green <|> blue + +handful :: Parser Handful +handful = space *> (flip (,) <$> read <$> many1 digit) <* space <*> color + +set = M.fromList <$> (sepBy handful $ string ",") +game = string "Game " *> ((,) <$> read <$> many1 digit) <* string ":" <*> sepBy set (string ";") + +solution :: Game -> Maybe Int +solution (i,m) = do + let m' = M.unionsWith max m + guard $ M.findWithDefault 0 Red m' <= 12 + guard $ M.findWithDefault 0 Green m' <= 13 + guard $ M.findWithDefault 0 Blue m' <= 14 + return i + +main = head <$> getArgs >>= readFile >>= print . sum . catMaybes . map solution . catMaybes . map (either (const Nothing) Just . parse game "") <$> lines \ No newline at end of file -- cgit 1.4.1