Skip to main content

aoc/year2022/
day09.rs

1//! # Rope Bridge
2//!
3//! This solution relies on the [`Point`] utility module. Two dimensional problems are common in
4//! Advent of Code, so having a decent `Point` (or `Coord` or `Pos`) implementation is convenient.
5use crate::util::grid::*;
6use crate::util::parse::*;
7use crate::util::point::*;
8
9type Input = (u32, u32);
10
11/// Converts input lines into a pair of [`Point`] and integer amount, to indicate direction and
12/// magnitude respectively. Then determines the maximum extent of the head so that we can allocate
13/// a two-dimensional grid.
14pub fn parse(input: &str) -> Input {
15    let steps = input.bytes().filter(u8::is_ascii_alphabetic).map(Point::from);
16    let amounts = input.iter_signed();
17    let pairs: Vec<_> = steps.zip(amounts).collect();
18
19    // Determine maximum extents.
20    let (x1, y1, x2, y2, _) =
21        pairs.iter().fold((0, 0, 0, 0, ORIGIN), |(x1, y1, x2, y2, point), &(step, amount)| {
22            let next = point + step * amount;
23            (x1.min(next.x), y1.min(next.y), x2.max(next.x), y2.max(next.y), next)
24        });
25
26    let mut part_one = 1;
27    let mut part_two = 2;
28    let start = Point::new(-x1, -y1);
29    let mut rope = [start; 10];
30    let mut grid = Grid::new(x2 - x1 + 1, y2 - y1 + 1, 0_u8);
31
32    // Knots only record their position after the second knot moves, so mark the starting square
33    // upfront for both parts.
34    grid[start] = 3;
35
36    for (step, amount) in pairs {
37        for _ in 0..amount {
38            let head = rope[0];
39            rope[0] += step;
40
41            // The second knot only moves when the head pulls apart from it. As the head only moves
42            // horizontally or vertically, the second knot always lands on the head's old position.
43            let delta = rope[0] - rope[1];
44            if delta.x.abs() <= 1 && delta.y.abs() <= 1 {
45                continue;
46            }
47
48            rope[1] = head;
49            part_one += u32::from(!grid[head] & 1);
50            grid[head] |= 1;
51
52            // Two knots are considered "apart" if they are not diagonally adjacent, that is
53            // the absolute distance in either x or y axes is greater than 1.
54            for i in 2..10 {
55                let delta = rope[i - 1] - rope[i];
56                if delta.x.abs() <= 1 && delta.y.abs() <= 1 {
57                    break;
58                }
59                rope[i] += Point::new(delta.x.signum(), delta.y.signum());
60            }
61
62            part_two += u32::from(!grid[rope[9]] & 2);
63            grid[rope[9]] |= 2;
64        }
65    }
66
67    (part_one, part_two >> 1)
68}
69
70pub fn part1(input: &Input) -> u32 {
71    input.0
72}
73
74pub fn part2(input: &Input) -> u32 {
75    input.1
76}