-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday09.rs
82 lines (71 loc) · 2.35 KB
/
day09.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::str::FromStr;
use crate::utils::{coords::Coordinates, directions::Direction, v2::solver};
use map_macro::hash_set;
use num_integer::Roots;
use scan_fmt::scan_fmt;
struct Vector {
direction: Direction,
displacement: i32,
}
impl FromStr for Vector {
type Err = ();
fn from_str(l: &str) -> Result<Self, Self::Err> {
let (direction, displacement) = scan_fmt!(l, "{} {}", String, i32).unwrap();
let direction = Direction::from_str(&direction, "U", "D", "L", "R");
Ok(Self {
direction,
displacement,
})
}
}
pub struct Solver;
impl solver::Solver<2022, 9> for Solver {
type Part1 = usize;
type Part2 = usize;
fn solve_part_one(&self, input: &str) -> Self::Part1 {
let vectors = input.lines().filter_map(|l| l.parse::<Vector>().ok());
let mut head = Coordinates::origin();
let mut tail = Coordinates::origin();
let mut visited = hash_set![tail];
for Vector {
direction,
displacement,
} in vectors
{
let dest = head.step_by(direction, displacement);
for head in head.manhattan_path(dest) {
if tail.euclidean_distance_squared(head).sqrt() < 2 {
continue;
}
tail = tail.euclidean_step(head);
visited.insert(tail);
}
head = dest;
}
visited.len()
}
fn solve_part_two(&self, input: &str) -> Self::Part2 {
let vectors = input.lines().filter_map(|l| l.parse::<Vector>().ok());
let mut rope = vec![Coordinates::origin(); 10];
let mut visited = hash_set![Coordinates::origin()];
for Vector {
direction,
displacement,
} in vectors
{
let dest = rope[0].step_by(direction, displacement);
for head in rope[0].manhattan_path(dest) {
rope[0] = head;
for i in 1..10 {
// rope[i] is the "tail", rope[i-1] is the "head"
if rope[i].euclidean_distance_squared(rope[i - 1]).sqrt() < 2 {
continue;
}
rope[i] = rope[i].euclidean_step(rope[i - 1]);
}
visited.insert(rope[9]);
}
}
visited.len()
}
}