summary refs log tree commit diff
path: root/2/2.hs
diff options
context:
space:
mode:
authortzlil <tzlils@protonmail.com>2023-12-02 13:57:02 +0200
committertzlil <tzlils@protonmail.com>2023-12-02 13:57:02 +0200
commit1552251e0ecf7915f682464eb3e71974ec41633d (patch)
treec3a26a68faf29970d397bd5e3e64da6262087590 /2/2.hs
solved day2
Diffstat (limited to '2/2.hs')
-rw-r--r--2/2.hs31
1 files changed, 31 insertions, 0 deletions
diff --git a/2/2.hs b/2/2.hs
new file mode 100644
index 0000000..0d1f855
--- /dev/null
+++ b/2/2.hs
@@ -0,0 +1,31 @@
+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 -> Int
+solution = product . M.elems . M.unionsWith max . snd
+
+main = head <$> getArgs >>= readFile >>= print . sum . map solution . catMaybes . map (either (const Nothing) Just . parse game "") <$> lines
\ No newline at end of file