Skip to main content

aoc/year2023/
day03.rs

1//! # Gear Ratios
2use crate::util::grid::*;
3use crate::util::parse::*;
4use crate::util::point::*;
5
6pub struct Input {
7    grid: Grid<u8>,
8    seen: Grid<usize>,
9    parts: Vec<u32>,
10}
11
12pub fn parse(input: &str) -> Input {
13    // The newline at the end of each row stops numbers wrapping onto the next row
14    // and the border keeps neighbor lookups in bounds.
15    let grid = Grid::parse_with_border(input);
16    // In order to tell if we've already seen a number before, store its index at the location
17    // of every digit, using zero to indicate no value. For example:
18    // `467..114..` => `1110022200`
19    let mut seen = grid.same_size_with(0);
20    // Stores each unique part number. The first value is a dummy placeholder.
21    let mut parts = vec![0];
22    let mut number = 0;
23
24    for (i, &b) in grid.bytes.iter().enumerate() {
25        if b.is_ascii_digit() {
26            // Parse contiguous groups of digits.
27            seen.bytes[i] = parts.len();
28            number = 10 * number + b.to_decimal::<u32>();
29        } else if number > 0 {
30            // If not a digit then finish the current number.
31            parts.push(number);
32            number = 0;
33        }
34    }
35
36    Input { grid, seen, parts }
37}
38
39/// Sum all part numbers adjacent to at least one symbol.
40pub fn part1(input: &Input) -> u32 {
41    let Input { grid, seen, parts } = input;
42    let mut parts = parts.clone();
43    let mut result = 0;
44
45    // Skip the newline border.
46    for y in 1..grid.height - 1 {
47        for x in 1..grid.width {
48            let p = Point::new(x, y);
49            let b = grid[p];
50
51            if !b.is_ascii_digit() && b != b'.' {
52                for d in DIAGONAL {
53                    let index = seen[p + d];
54                    if index != 0 {
55                        result += parts[index];
56                        // Only count each number once when it is adjacent to multiple symbols.
57                        parts[index] = 0;
58                    }
59                }
60            }
61        }
62    }
63
64    result
65}
66
67/// Sum all gears adjacent to exactly two part numbers.
68pub fn part2(input: &Input) -> u32 {
69    let Input { grid, seen, parts } = input;
70    let mut result = 0;
71
72    for y in 1..grid.height - 1 {
73        for x in 1..grid.width {
74            let p = Point::new(x, y);
75
76            if grid[p] == b'*' {
77                let mut previous = 0;
78                let mut distinct = 0;
79                let mut subtotal = 1;
80
81                // Rely on the left to right and top to bottom order of DIAGONAL
82                // to detect distinct numbers.
83                for d in DIAGONAL {
84                    let index = seen[p + d];
85                    if index != 0 && index != previous {
86                        previous = index;
87                        distinct += 1;
88                        subtotal *= parts[index];
89                    }
90                }
91
92                if distinct == 2 {
93                    result += subtotal;
94                }
95            }
96        }
97    }
98
99    result
100}