Skip to main content

aoc/year2018/
day15.rs

1//! # Beverage Bandits
2//!
3//! This problem is notoriously tricky due to the finicky rules that must be followed precisely and
4//! the fact that not all inputs trigger all edge cases. However, from a performance aspect most
5//! of the time is consumed finding the nearest target whenever a unit needs to move.
6//!
7//! For each move we perform two [BFS](https://en.wikipedia.org/wiki/Breadth-first_search).
8//! The first search from the current unit finds the nearest target in reading order.
9//! The second *reverse* search from the target to the current unit finds the correct direction
10//! to move.
11//!
12//! Since the cave dimensions are 32 x 32 we use a fixed-size array of bitmasks stored in `u32`
13//! to execute each BFS efficiently. Each step we expand the frontier using the bitwise logic
14//! applied to each row:
15//!
16//! ```none
17//! (previous | (current << 1) | current | (current >> 1) | next) & !walls
18//! ```
19//!
20//! We represent the goal using bits and stop searching once that intersects with the frontier.
21//! First example:
22//!
23//! * Goblin's turn.
24//! * We should choose the first target square in reading order (to the right of the nearest elf).
25//! * There are two equal shortest paths to that square, so we should choose the first *step* in
26//!   reading order (up).
27//! ```none
28//! Map        Walls      In Range
29//! #######    1111111    0000000
30//! #E    #    1000001    0110000
31//! # E   #    1000001    0111000
32//! #    G#    1000001    0010000
33//! #######    1111111    0000000
34//!
35//! Forward BFS frontier                        Intersection
36//! 0000000    0000000    0000000    0000000    0000000
37//! 0000000    0000000    0000010    0000110    0000000
38//! 0000000 => 0000010 => 0000110 => 0001110 => 0001000 <= Choose first target square
39//! 0000010    0000110    0001110    0011110    0010000    in reading order
40//! 0000000    0000000    0000000    0000000    0000000
41//!
42//! Reverse BFS frontier             Intersection
43//! 0000000    0000000    0000000    0000000
44//! 0000000    0001000    0011100    0000000
45//! 0001000 => 0011100 => 0111110 => 0000010 <= Choose first step
46//! 0000000    0001000    0011100    0000100    in reading order
47//! 0000000    0000000    0000000    0000000
48//! ```
49//!
50//! Choosing the first intersection in reading order the Goblin correctly moves upwards.
51//! Second example:
52//!
53//! * Elf's turn.
54//! * There are two equal shortest paths.
55//! * We should choose the first *unit* in reading order (left).
56//! ```none
57//! Map             Walls           In Range
58//! ###########    11111111111    00000000000
59//! #G..#....G#    10001000001    01100000110
60//! ###..E#####    11100011111    00000000000
61//! ###########    11111111111    00000000000
62//!
63//! Forward BFS frontier                                                       Intersection
64//! 00000000000    00000000000    00000000000    00000000000    00000000000    00000000000
65//! 00000000000    00000100000    00000110000    00010111000    00110111100    00100000100
66//! 00000100000 => 00001100000 => 00011100000 => 00011100000 => 00011100000 => 00000000000
67//! 00000000000    00000000000    00000000000    00000000000    00000000000    00000000000
68//!
69//! Reverse BFS frontier                                        Intersection
70//! 00000000000    00000000000    00000000000    00000000000    00000000000
71//! 00100000000    01110000000    01110000000    01110000000    00000000000
72//! 00000000000 => 00000000000 => 00010000000 => 00011000000 => 00001000000
73//! 00000000000    00000000000    00000000000    00000000000    00000000000
74//! ```
75//!
76//! Choosing the first intersection in reading order the Elf correctly moves left.
77use crate::util::grid::*;
78use crate::util::point::*;
79use crate::util::thread::*;
80
81const READING_ORDER: [Point; 4] = [UP, LEFT, RIGHT, DOWN];
82
83pub struct Input {
84    walls: [u32; 32],
85    elves: Vec<Point>,
86    goblins: Vec<Point>,
87}
88
89#[derive(Clone, Copy, Eq, PartialEq)]
90enum Kind {
91    Elf,
92    Goblin,
93}
94
95struct Unit {
96    position: Point,
97    kind: Kind,
98    health: i32,
99    power: i32,
100}
101
102/// Parse the input into a bitmask for the cave walls
103/// and a list of point coordinates for each Elf and Goblin.
104pub fn parse(input: &str) -> Input {
105    let grid = Grid::parse(input);
106
107    let mut walls = [0; 32];
108    let mut elves = Vec::new();
109    let mut goblins = Vec::new();
110
111    for position in grid.points() {
112        match grid[position] {
113            b'#' => set_bit(&mut walls, position),
114            b'E' => elves.push(position),
115            b'G' => goblins.push(position),
116            _ => (),
117        }
118    }
119
120    Input { walls, elves, goblins }
121}
122
123/// Simulate a full fight until only Elves or only Goblins remain.
124pub fn part1(input: &Input) -> i32 {
125    fight(input, 3, false).unwrap()
126}
127
128/// Find the lowest attack power where no Elf dies. We can short circuit any fight once a
129/// single Elf is killed. Since each fight is independent we can parallelize the search over
130/// multiple threads.
131pub fn part2(input: &Input) -> i32 {
132    let iter = AtomicIter::new(4, 1);
133
134    // Use as many cores as possible to parallelize the search.
135    let result = spawn(|| worker(input, &iter));
136    // Find lowest possible power.
137    result.into_iter().flatten().min_by_key(|&(eap, _)| eap).map(|(_, score)| score).unwrap()
138}
139
140fn worker(input: &Input, iter: &AtomicIter) -> Option<(u32, i32)> {
141    while let Some(power) = iter.next() {
142        // If the Elves win then signal all threads to stop.
143        if let Some(score) = fight(input, power as i32, true) {
144            iter.stop();
145            return Some((power, score));
146        }
147    }
148
149    None
150}
151
152/// Careful implementation of the game rules.
153fn fight(input: &Input, elf_attack_power: i32, part_two: bool) -> Option<i32> {
154    let mut units = Vec::new();
155    let mut elves = input.elves.len();
156    let mut goblins = input.goblins.len();
157    let mut grid = Grid::new(32, 32, None);
158
159    // Initialize each unit.
160    for &position in &input.elves {
161        units.push(Unit { position, kind: Kind::Elf, health: 200, power: elf_attack_power });
162    }
163    for &position in &input.goblins {
164        units.push(Unit { position, kind: Kind::Goblin, health: 200, power: 3 });
165    }
166
167    for turn in 0.. {
168        // Remove dead units for efficiency.
169        units.retain(|u| u.health > 0);
170        // Units take turns in reading order.
171        units.sort_unstable_by_key(|u| 32 * u.position.y + u.position.x);
172        // Grid is used for reverse lookup from location to index.
173        units.iter().enumerate().for_each(|(i, u)| grid[u.position] = Some(i));
174
175        for index in 0..units.len() {
176            let Unit { position, kind, health, power } = units[index];
177
178            // Unit may have been killed during this turn.
179            if health <= 0 {
180                continue;
181            }
182
183            // Check if there are no more remaining targets then return *complete* turns.
184            // Determining a complete turn is subtle. If the last unit to act (in reading order)
185            // kills the last remaining enemy then that counts as a complete turn. Otherwise, the
186            // turn is considered incomplete and doesn't count.
187            if elves == 0 || goblins == 0 {
188                return Some(turn * units.iter().map(|u| u.health.max(0)).sum::<i32>());
189            }
190
191            // Search for neighboring enemies.
192            let mut nearby = attack(&grid, &units, position, kind);
193
194            // If no enemy next to unit then move toward nearest enemy in reading order,
195            // breaking equal distance ties in reading order.
196            if nearby.is_none()
197                && let Some(next) = double_bfs(input.walls, &units, position, kind)
198            {
199                grid[position] = None;
200                grid[next] = Some(index);
201                units[index].position = next;
202
203                nearby = attack(&grid, &units, next, kind);
204            }
205
206            // Attack enemy if possible.
207            if let Some(target) = nearby {
208                units[target].health -= power;
209
210                if units[target].health <= 0 {
211                    grid[units[target].position] = None;
212
213                    // For part two, short circuit if a single elf is killed.
214                    match units[target].kind {
215                        Kind::Elf if part_two => return None,
216                        Kind::Elf => elves -= 1,
217                        Kind::Goblin => goblins -= 1,
218                    }
219                }
220            }
221        }
222    }
223
224    unreachable!()
225}
226
227/// Search for weakest neighboring enemy. Equal health ties are broken in reading order.
228fn attack(grid: &Grid<Option<usize>>, units: &[Unit], point: Point, kind: Kind) -> Option<usize> {
229    READING_ORDER
230        .iter()
231        .filter_map(|&o| grid[point + o])
232        .filter(|&next| units[next].kind != kind)
233        .min_by_key(|&next| units[next].health)
234}
235
236/// Performs two BFS searches. The first search from the current unit finds the nearest target
237/// in reading order. The second reverse search from the target to the current unit finds the
238/// correct direction to move.
239fn double_bfs(mut walls: [u32; 32], units: &[Unit], point: Point, kind: Kind) -> Option<Point> {
240    let frontier = &mut [0; 32];
241    set_bit(frontier, point);
242
243    let walls = &mut walls;
244    let in_range = &mut [0; 32];
245
246    for unit in units.iter().filter(|u| u.health > 0) {
247        if unit.kind == kind {
248            // Units of the same type are obstacles.
249            set_bit(walls, unit.position);
250        } else {
251            // Add enemy units to the list of potential targets.
252            set_bit(in_range, unit.position);
253        }
254    }
255
256    // We're interested in the 4 orthogonal squares around each enemy unit.
257    expand(walls, in_range);
258
259    // Search for reachable squares. There could be no reachable squares, for example friendly
260    // units already have the enemy surrounded or are blocking the path.
261    while expand(walls, frontier) {
262        if let Some(target) = intersect(in_range, frontier) {
263            // Reverse search from target to determine correct movement direction.
264            let frontier = &mut [0; 32];
265            set_bit(frontier, target);
266
267            let in_range = &mut [0; 32];
268            set_bit(in_range, point);
269            expand(walls, in_range);
270
271            // This will always succeed as there was a path from the current unit.
272            loop {
273                expand(walls, frontier);
274                if let Some(target) = intersect(in_range, frontier) {
275                    return Some(target);
276                }
277            }
278        }
279    }
280
281    None
282}
283
284/// Use bitwise logic to expand the frontier. Returns a boolean indicating if the frontier
285/// actually expanded.
286fn expand(walls: &[u32], frontier: &mut [u32]) -> bool {
287    let mut previous = frontier[0];
288    let mut changed = 0;
289
290    for i in 1..31 {
291        let current = frontier[i];
292        let next = frontier[i + 1];
293
294        frontier[i] = (previous | (current << 1) | current | (current >> 1) | next) & !walls[i];
295
296        previous = current;
297        changed |= current ^ frontier[i];
298    }
299
300    changed != 0
301}
302
303/// Check if we have reached a target, returning the first target in reading order.
304fn intersect(in_range: &[u32], frontier: &[u32]) -> Option<Point> {
305    (1..31).find_map(|i| {
306        let both = in_range[i] & frontier[i];
307        both.lowest_one().map(|x| Point::new(x as i32, i as i32))
308    })
309}
310
311/// Convenience function to set a single bit from a point's location.
312#[inline]
313fn set_bit(slice: &mut [u32], point: Point) {
314    slice[point.y as usize] |= 1 << point.x;
315}