Skip to content

Instantly share code, notes, and snippets.

@saolsen
Created December 9, 2022 18:56
Show Gist options
  • Save saolsen/ec11913ddcafaa53f2ff478debccbd08 to your computer and use it in GitHub Desktop.
Save saolsen/ec11913ddcafaa53f2ff478debccbd08 to your computer and use it in GitHub Desktop.
aoc 2022 day09
use std::collections::HashSet;
fn parse<'a>(input: &'a str) -> impl Iterator<Item = (&'a str, u32)> + 'a {
input.split("\n").map(|line| {
let mut split = line.split(" ");
let dir = split.next().unwrap();
let steps = split.next().unwrap().parse::<u32>().unwrap();
(dir, steps)
})
}
fn main() {
let mut t_positions = HashSet::new();
t_positions.insert((0, 0));
let mut rope: Vec<(i32, i32)> = vec![(0, 0); 10];
for (dir, n) in parse(include_str!("day09_input.txt")) {
for _ in 0..n {
// move head
match dir {
"R" => rope[0].0 += 1,
"L" => rope[0].0 -= 1,
"U" => rope[0].1 += 1,
"D" => rope[0].1 -= 1,
_ => unimplemented!(),
}
// move tail pieces
for i in 1..10 {
let h = rope[i - 1];
let t = rope[i];
let x_dist = h.0 - t.0;
let y_dist = h.1 - t.1;
if x_dist.abs() > 1 || y_dist.abs() > 1 {
if x_dist != 0 {
rope[i].0 += x_dist / x_dist.abs();
}
if y_dist != 0 {
rope[i].1 += y_dist / y_dist.abs();
}
}
}
t_positions.insert(rope[9]);
}
}
eprintln!("num_tail_positions: {}", t_positions.len());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment