Skip to content

Commit 1544a16

Browse files
committed
P1
1 parent d2a2e5d commit 1544a16

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

19.hs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import Data.Char (isDigit)
2-
import Data.List (elemIndex)
2+
import Data.List (elemIndex, find)
33
import Data.Map qualified as M
44

55
main :: IO ()
6-
main = interact $ (++ "\n") . show . parse
6+
main = interact $ (++ "\n") . show . p1 . parse
77

88
type Workflows = M.Map String [Rule]
99
type Rule = (Maybe Condition, String)
@@ -13,14 +13,14 @@ type Part = [Int]
1313
parse :: String -> (Workflows, [Part])
1414
parse = both . lines
1515
where
16-
both s = let (a, b) = span (/= "") s in (workflows a, map part b)
16+
both s = let (a, b) = span (/= "") s in (workflows a, map part (drop 1 b))
1717
workflows = M.fromList . map workflow
1818
workflow s = (rules . drop 1) <$> break (== '{') s
1919
rules [] = []
2020
rules s = let (a, b) = break (`elem` ",}") s in rule a : rules (drop 1 b)
2121
rule s = case break (== ':') s of
2222
(r, []) -> (Nothing, r)
23-
(c, r) -> (Just (condition c), r)
23+
(c, r) -> (Just (condition c), drop 1 r)
2424
condition (p:c:rs) = case p `elemIndex` "xmas" of
2525
Just i -> (i, c, read rs)
2626
part s = case reads (snd $ break isDigit s) of
@@ -32,3 +32,11 @@ valid ws p = go "in"
3232
where
3333
go "A" = True
3434
go "R" = False
35+
go w = go $ next ((M.!) ws w)
36+
next ((Nothing, r) : _) = r
37+
next ((Just c, r) : rs) = if test c then r else next rs
38+
test (i, '<', v) = (p !! i) < v
39+
test (i, '>', v) = (p !! i) > v
40+
41+
p1 :: (Workflows, [Part]) -> Int
42+
p1 (workflows, parts) = sum . concat $ filter (valid workflows) parts

0 commit comments

Comments
 (0)