summary refs log tree commit diff
path: root/4/1.hs
blob: 275a04cbfd20b4061e71e6ca721ed7979617b5bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Prelude
import Text.Parsec.String (Parser)
import Text.Parsec
import System.Environment
import Control.Monad
import qualified Data.Set as S

type Card = (Int, S.Set Int, S.Set Int)

numbers = S.fromList <$> ((many1 space) *> sepEndBy (read <$> many1 digit) (many1 space))

card :: Parser Card
card = (,,) <$> (string "Card" *> spaces *> (read <$> many1 digit) <* char ':') <*> numbers <* (char '|') <*> numbers

cards = many1 card

solution :: [Card] -> Int
solution xs = sum $ map f xs where 
    f (id,picked,winning) = case (length $ S.intersection picked winning) of
        0 -> 0
        n -> 2 ^ (pred n)

main = liftM2 (>>=) readFile (((print . solution . either (error.show) id) .) . parse cards) =<< head <$> getArgs