summary refs log tree commit diff
path: root/4/2.hs
diff options
context:
space:
mode:
Diffstat (limited to '4/2.hs')
-rw-r--r--4/2.hs24
1 files changed, 24 insertions, 0 deletions
diff --git a/4/2.hs b/4/2.hs
new file mode 100644
index 0000000..b728231
--- /dev/null
+++ b/4/2.hs
@@ -0,0 +1,24 @@
+import Prelude
+import Text.Parsec.String (Parser)
+import Text.Parsec
+import System.Environment
+import Control.Monad
+import qualified Data.Set as S
+import Data.Maybe
+
+type Card = (S.Set Int, S.Set Int)
+
+numbers = S.fromList <$> ((many1 space) *> sepEndBy (read <$> many1 digit) (many1 space))
+
+card :: Parser Card
+card = string "Card" *> spaces *> many1 digit *> char ':' *> liftM2 (,) (numbers <* (char '|')) numbers
+
+cards = many1 card
+
+solution :: [Card] -> Int
+solution = sum . map (+1) . foldr f [] where
+    f (picked,winning) ws = w : ws where
+        m = length $ S.intersection picked winning
+        w = m + sum (take m ws)
+
+main = liftM2 (>>=) readFile (((print . solution . either (error.show) id) .) . parse cards) =<< head <$> getArgs
\ No newline at end of file