1
0
This commit is contained in:
Jack Bond-Preston 2022-12-26 21:31:55 +00:00
parent 2c1323095f
commit 02445824a6
5 changed files with 2082 additions and 0 deletions

View File

@ -9,4 +9,5 @@ members = [
"day6",
"day7",
"day8",
"day9",
]

9
day9/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "day9"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nalgebra = "0.31.4"

2000
day9/input.txt Normal file

File diff suppressed because it is too large Load Diff

8
day9/sample_input.txt Normal file
View File

@ -0,0 +1,8 @@
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20

64
day9/src/main.rs Normal file
View File

@ -0,0 +1,64 @@
use std::collections::HashSet;
use nalgebra::base::Vector2;
type IVec2 = Vector2<i32>;
const RIGHT: IVec2 = IVec2::new(1, 0);
const LEFT: IVec2 = IVec2::new(-1, 0);
const UP: IVec2 = IVec2::new(0, 1);
const DOWN: IVec2 = IVec2::new(0, -1);
const ZERO: IVec2 = IVec2::new(0, 0);
fn main() {
const INPUT: &str = include_str!("../input.txt");
let mut visited: HashSet<IVec2> = HashSet::new();
let mut knots: [IVec2; 10] = [ZERO; 10];
for line in INPUT.lines() {
let (dir, steps) = line.split_once(' ').unwrap();
let dir: IVec2 = match dir.chars().next().unwrap() {
'R' => RIGHT,
'L' => LEFT,
'U' => UP,
'D' => DOWN,
_ => ZERO,
};
let steps: u32 = steps.parse().unwrap();
for _ in 0..steps {
*knots.get_mut(0).unwrap() += dir;
for i in 1..knots.len() {
let diff: IVec2;
{
let knot = knots.get(i).unwrap();
let prev = knots.get(i - 1).unwrap();
diff = *prev - *knot;
}
let knot = knots.get_mut(i).unwrap();
if diff.x.abs() > 1 || diff.y.abs() > 1 {
// need to move
if diff.x == 0 {
knot.y += diff.y.signum();
} else if diff.y == 0 {
knot.x += diff.x.signum();
} else {
knot.x += diff.x.signum();
knot.y += diff.y.signum();
}
}
if i == 9 {
visited.insert(*knot);
}
}
}
}
println!("{}", visited.len());
}