-
Notifications
You must be signed in to change notification settings - Fork 0
/
09.rs
71 lines (60 loc) · 1.63 KB
/
09.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
#![feature(test)]
use aoc::grid::Direction;
use rustc_hash::FxHashSet;
type Input = Vec<Motion>;
#[derive(Debug)]
struct Motion {
direction: Direction,
count: u32,
}
struct Solver<'a> {
motions: &'a [Motion],
knots: Vec<(isize, isize)>,
visited: FxHashSet<(isize, isize)>,
}
impl<'a> Solver<'a> {
fn new(input: &'a Input, n: usize) -> Self {
Self {
motions: input,
knots: vec![(0, 0); n],
visited: FxHashSet::default(),
}
}
fn follow(&mut self, i: usize) {
let p = self.knots[i - 1].0 - self.knots[i].0;
let q = self.knots[i - 1].1 - self.knots[i].1;
if p.abs() > 1 || q.abs() > 1 {
self.knots[i] = (
self.knots[i].0 + p.clamp(-1, 1),
self.knots[i].1 + q.clamp(-1, 1),
);
}
}
fn solve(mut self) -> usize {
for Motion { direction, count } in self.motions {
for _ in 0..*count {
self.knots[0] = direction.step_signed(self.knots[0]);
(1..self.knots.len()).for_each(|i| self.follow(i));
self.visited.insert(*self.knots.last().unwrap());
}
}
self.visited.len()
}
}
fn setup(input: &str) -> Input {
input
.trim()
.lines()
.map(|line| Motion {
direction: line.chars().next().unwrap().into(),
count: line[2..].parse().unwrap(),
})
.collect()
}
fn part1(input: &Input) -> usize {
Solver::new(input, 2).solve()
}
fn part2(input: &Input) -> usize {
Solver::new(input, 10).solve()
}
aoc::main!(2022, 9, ex: 1, 2);