1use crate::util::grid::*;
6use crate::util::parse::*;
7use crate::util::point::*;
8
9type Input = (u32, u32);
10
11pub 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 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 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 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 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}