Skip to content

Commit 4005d98

Browse files
committed
Tweak
1 parent ec15504 commit 4005d98

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

19.hs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Data.Char (isDigit)
22
import Data.List (elemIndex, find)
3+
import Data.Map ((!))
34
import Data.Map qualified as M
45
import Control.Arrow ((&&&))
56

@@ -33,7 +34,7 @@ valid ws p = go "in"
3334
where
3435
go "A" = True
3536
go "R" = False
36-
go w = go $ next ((M.!) ws w)
37+
go w = go $ next (ws ! w)
3738
next ((Nothing, r) : _) = r
3839
next ((Just c, r) : rs) = if test c then r else next rs
3940
test (i, '<', v) = (p !! i) < v
@@ -42,25 +43,27 @@ valid ws p = go "in"
4243
p1 :: (Workflows, [Part]) -> Int
4344
p1 (workflows, parts) = sum . concat $ filter (valid workflows) parts
4445

45-
type Ranges = [(Int, Int)]
46-
type Thread = (Ranges, String)
46+
type Ranges = [(Int, Int)] -- 4 ranges, one for each attribute of a part
47+
type Thread = (Ranges, String) -- Ranges undergoing a particular workflow
4748

4849
validCombinations :: Workflows -> Int
4950
validCombinations ws = go [(replicate 4 (1, 4000), "in")]
5051
where
5152
combo :: Ranges -> Int
52-
combo ranges = product $ map ((+1) . uncurry subtract) ranges
53-
rules w = ((M.!) ws w)
53+
combo = product . map ((+1) . uncurry subtract)
54+
5455
go :: [Thread] -> Int
5556
go [] = 0
5657
go ((rs, "A") : xs) = combo rs + go xs
5758
go ((_, "R") : xs) = go xs
58-
go ((rs, w) : xs) = go $ (splitThreads rs (rules w)) ++ xs
59+
go ((rs, w) : xs) = go $ splitThreads rs (ws ! w) ++ xs
60+
5961
splitThreads :: Ranges -> [Rule] -> [Thread]
6062
splitThreads rs ((Nothing, w) : _) = [(rs, w)]
6163
splitThreads rs ((Just c, w) : rest) =
6264
let (matching, notMatching) = split rs c
6365
in [(matching, w)] ++ splitThreads notMatching rest
66+
6467
split :: Ranges -> Condition -> (Ranges, Ranges)
6568
split ranges (i, op, v) = foldl f ([], []) (zip [0..] ranges)
6669
where f (m, n) (j, r) | i == j = let (match, nomatch) = split' r op v

0 commit comments

Comments
 (0)