1use 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 let grid = Grid::parse_with_border(input);
16 let mut seen = grid.same_size_with(0);
20 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 seen.bytes[i] = parts.len();
28 number = 10 * number + b.to_decimal::<u32>();
29 } else if number > 0 {
30 parts.push(number);
32 number = 0;
33 }
34 }
35
36 Input { grid, seen, parts }
37}
38
39pub 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 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 parts[index] = 0;
58 }
59 }
60 }
61 }
62 }
63
64 result
65}
66
67pub 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 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}