summary refs log tree commit diff
path: root/2/2.hs
blob: 0d1f855096aa74a49abcf66962f86698b0dd98f9 (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
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