1use std::ops::Range;
18
19use crate::util::hash::*;
20use crate::util::iter::*;
21use crate::util::parse::*;
22
23struct Rule<'a> {
24 range: Range<u32>,
25 category: usize,
26 next: &'a str,
27}
28
29pub struct Input<'a> {
30 workflows: FastMap<&'a str, Vec<Rule<'a>>>,
31 parts: &'a str,
32}
33
34pub fn parse(input: &str) -> Input<'_> {
38 let (prefix, suffix) = input.split_once("\n\n").unwrap();
39 let mut workflows = FastMap::with_capacity(1_000);
40
41 for line in prefix.lines() {
42 let mut iter = line.split(['{', ':', ',', '}']);
43 let key = iter.next().unwrap();
44
45 let rules = iter
46 .chunk::<2>()
47 .map(|[first, second]| {
48 if second.is_empty() {
49 return Rule { range: 1..4001, category: 0, next: first };
51 }
52
53 let category = b"xmas".iter().position(|&b| b == first.as_bytes()[0]).unwrap();
56
57 let value = first[2..].unsigned();
59 let range = match first.as_bytes()[1] {
60 b'<' => 1..value,
61 b'>' => value + 1..4001,
62 _ => unreachable!(),
63 };
64
65 Rule { range, category, next: second }
66 })
67 .collect();
68
69 workflows.insert(key, rules);
70 }
71
72 Input { workflows, parts: suffix }
73}
74
75pub fn part1(input: &Input<'_>) -> u32 {
76 let Input { workflows, parts } = input;
77
78 parts
80 .iter_unsigned()
81 .chunk::<4>()
82 .filter(|part| {
83 let mut key = "in";
84
85 while key.len() > 1 {
86 key = workflows[key]
88 .iter()
89 .find(|rule| rule.range.contains(&part[rule.category]))
90 .unwrap()
91 .next;
92 }
93
94 key == "A"
95 })
96 .flatten()
97 .sum()
98}
99
100pub fn part2(input: &Input<'_>) -> u64 {
101 let Input { workflows, .. } = input;
102 let mut result = 0;
103 let mut todo = vec![("in", 0, [(1, 4001); 4])];
104
105 while let Some((key, index, mut part)) = todo.pop() {
106 if key.len() == 1 {
107 if key == "A" {
108 result += part.iter().map(|(s, e)| (e - s) as u64).product::<u64>();
109 }
110 continue;
111 }
112
113 let Rule { range, category, next } = &workflows[key][index];
114 let category = *category;
115 let (s1, e1) = part[category];
116
117 let x1 = s1.max(range.start);
119 let x2 = e1.min(range.end);
120
121 if x1 >= x2 {
122 todo.push((key, index + 1, part));
124 } else {
125 part[category] = (x1, x2);
127 todo.push((next, 0, part));
128
129 if s1 < x1 {
131 part[category] = (s1, x1);
132 todo.push((key, index + 1, part));
133 }
134
135 if x2 < e1 {
137 part[category] = (x2, e1);
138 todo.push((key, index + 1, part));
139 }
140 }
141 }
142
143 result
144}