1use crate::util::parse::*;
11use crate::util::thread::*;
12
13pub struct Input {
14 immune: Vec<Group>,
15 infection: Vec<Group>,
16}
17
18#[derive(Clone, Copy, Eq, PartialEq)]
19enum Kind {
20 Immune,
21 Infection,
22 Draw,
23}
24
25#[derive(Clone, Copy)]
26struct Group {
27 units: i32,
28 hit_points: i32,
29 damage: i32,
30 initiative: i32,
31 weak: u32,
32 immune: u32,
33 attack: u32,
34 chosen: u32,
35}
36
37impl Group {
39 fn effective_power(&self) -> i32 {
40 self.units * self.damage
41 }
42
43 fn actual_damage(&self, other: &Self) -> i32 {
45 if self.attack & other.weak != 0 {
46 2 * self.effective_power()
47 } else if self.attack & other.immune == 0 {
48 self.effective_power()
49 } else {
50 0
51 }
52 }
53
54 fn target_selection_order(&self) -> (i32, i32) {
55 (-self.effective_power(), -self.initiative)
56 }
57
58 fn attack(&self, defender: &mut Self) -> i32 {
59 let damage = self.actual_damage(defender).max(0);
62 let amount = damage / defender.hit_points;
63 defender.units -= amount;
64 amount
65 }
66}
67
68pub fn parse(input: &str) -> Input {
69 let (first, second) = input.split_once("\n\n").unwrap();
70 let immune = parse_group(first);
71 let infection = parse_group(second);
72 Input { immune, infection }
73}
74
75pub fn part1(input: &Input) -> i32 {
76 let (_, units) = fight(input, 0);
77 units
78}
79
80pub fn part2(input: &Input) -> i32 {
81 let iter = AtomicIter::new(1, 1);
82
83 let result = spawn(|| worker(input, &iter));
85 result.into_iter().flatten().min_by_key(|&(boost, _)| boost).map(|(_, units)| units).unwrap()
87}
88
89fn worker(input: &Input, iter: &AtomicIter) -> Option<(u32, i32)> {
90 while let Some(boost) = iter.next() {
91 let (kind, units) = fight(input, boost as i32);
93
94 if kind == Kind::Immune {
95 iter.stop();
96 return Some((boost, units));
97 }
98 }
99
100 None
101}
102
103fn fight(input: &Input, boost: i32) -> (Kind, i32) {
104 let mut immune = input.immune.clone();
105 let mut infection = input.infection.clone();
106 let mut attacks = vec![None; immune.len() + infection.len()];
107
108 immune.iter_mut().for_each(|group| group.damage += boost);
110
111 for turn in 1.. {
112 let mut target_selection = |attacker: &[Group], defender: &mut [Group], kind: Kind| {
114 for (from, group) in attacker.iter().enumerate() {
115 let target = (0..defender.len())
116 .filter(|&to| {
117 defender[to].chosen < turn && group.actual_damage(&defender[to]) > 0
118 })
119 .max_by_key(|&to| {
120 (
121 group.actual_damage(&defender[to]),
122 defender[to].effective_power(),
123 defender[to].initiative,
124 )
125 });
126
127 if let Some(to) = target {
128 let index = attacks.len() - group.initiative as usize;
130 defender[to].chosen = turn;
131 attacks[index] = Some((kind, from, to));
132 }
133 }
134 };
135
136 immune.sort_unstable_by_key(Group::target_selection_order);
138 infection.sort_unstable_by_key(Group::target_selection_order);
139
140 target_selection(&immune, &mut infection, Kind::Immune);
141 target_selection(&infection, &mut immune, Kind::Infection);
142
143 let killed: i32 = attacks
145 .iter_mut()
146 .filter_map(Option::take)
147 .map(|(kind, from, to)| {
148 if kind == Kind::Immune {
149 immune[from].attack(&mut infection[to])
150 } else {
151 infection[from].attack(&mut immune[to])
152 }
153 })
154 .sum();
155
156 if killed == 0 {
158 return (Kind::Draw, 0);
159 }
160
161 immune.retain(|group| group.units > 0);
163 infection.retain(|group| group.units > 0);
164
165 if immune.is_empty() {
166 return (Kind::Infection, infection.iter().map(|group| group.units).sum());
167 }
168 if infection.is_empty() {
169 return (Kind::Immune, immune.iter().map(|group| group.units).sum());
170 }
171 }
172
173 unreachable!()
174}
175
176fn parse_group(input: &str) -> Vec<Group> {
178 let delimiters = [' ', '(', ')', ',', ';'];
179 input
180 .lines()
181 .skip(1)
182 .map(|line| {
183 let tokens: Vec<_> = line.split(delimiters).collect();
184
185 let units = tokens[0].signed();
186 let hit_points = tokens[4].signed();
187 let damage = tokens[tokens.len() - 6].signed();
188 let initiative = tokens[tokens.len() - 1].signed();
189 let attack = mask(tokens[tokens.len() - 5]);
190 let weak = parse_list(&tokens, "weak");
191 let immune = parse_list(&tokens, "immune");
192 let chosen = 0;
193
194 Group { units, hit_points, damage, initiative, weak, immune, attack, chosen }
195 })
196 .collect()
197}
198
199fn parse_list(tokens: &[&str], start: &str) -> u32 {
201 let end = ["weak", "immune", "with"];
202 tokens
203 .iter()
204 .skip_while(|&&t| t != start)
205 .skip(2)
207 .take_while(|&&t| !end.contains(&t))
208 .filter(|t| !t.is_empty())
210 .fold(0, |elements, &t| elements | mask(t))
211}
212
213fn mask(element: &str) -> u32 {
216 1 << (element.as_bytes()[0] - b'a')
217}