day 9
This commit is contained in:
64
day9/src/main.rs
Normal file
64
day9/src/main.rs
Normal 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());
|
||||
}
|
Reference in New Issue
Block a user