summary refs log tree commit diff
path: root/2/1.hs
blob: 726f95cf378a14b1265d6ed1048f55fb9bc0fbc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 (Show,Eq,Ord)
type Set = M.Map Color Int
type Game = (Int, [Set])

red = string "red" *>  pure Red
green = string "green" *>  pure Green
blue = string "blue" *>  pure Blue

color = red <|> green <|> blue 

handful = liftM2 (flip (,)) (space *> (read <$> many1 digit)) (space *> color)

set = M.fromList <$> (sepBy handful $ string ",")
game = liftM2 (,) (string "Game " *> (read <$> many1 digit)) (string ":" *> sepBy set (string ";"))

games = sepBy game newline

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 = liftM2 (>>=) readFile (((print . sum . catMaybes . map solution . either (error.show) id) .) . parse games) =<< head <$> getArgs