dumb_shit/2022-aoc/src/d9.rs

65 lines
1.6 KiB
Rust
Raw Normal View History

2022-12-09 23:49:09 +00:00
use std::collections::HashSet;
use aoc_runner_derive::{aoc as aoc_run, aoc_generator};
2022-12-10 01:09:33 +00:00
type Coord = (i32, i32);
2022-12-09 23:49:09 +00:00
#[aoc_generator(day9)]
2022-12-10 01:09:33 +00:00
fn parse_input(input: &str) -> Vec<Coord> {
2022-12-09 23:49:09 +00:00
let mut out = Vec::new();
let (mut x, mut y) = (0, 0);
out.push((x, y));
for line in input.lines() {
2022-12-10 01:09:33 +00:00
let (dir, num) = line.split_once(' ').unwrap();
let num: i32 = num.parse().unwrap();
2022-12-09 23:49:09 +00:00
for _ in 0..num {
match dir {
"U" => y += 1,
"D" => y -= 1,
"L" => x -= 1,
"R" => x += 1,
_ => unreachable!(),
}
out.push((x, y));
}
}
out
}
#[aoc_run(day9, part1)]
2022-12-10 01:09:33 +00:00
fn part1(input: &[Coord]) -> usize {
2022-12-09 23:49:09 +00:00
let mut tail = (0, 0);
let mut set = HashSet::new();
set.insert(tail);
for mv in input {
tail = new_tail(mv, &tail);
set.insert(tail);
}
set.len()
}
#[aoc_run(day9, part2)]
2022-12-10 01:09:33 +00:00
fn part2(input: &[Coord]) -> usize {
let mut knots = Vec::from_iter((0..9).map(|_| (0, 0)));
let mut set = HashSet::new();
set.insert((0, 0));
for mv in input {
let mut head = *mv;
for knot in knots.iter_mut() {
*knot = new_tail(&head, knot);
head = *knot;
}
set.insert(*knots.last().unwrap());
}
set.len()
2022-12-09 23:49:09 +00:00
}
2022-12-10 01:09:33 +00:00
fn new_tail(head: &Coord, tail: &Coord) -> Coord {
2022-12-09 23:49:09 +00:00
let dy = head.1 - tail.1;
let dx = head.0 - tail.0;
match (dx, dy) {
2022-12-10 00:01:08 +00:00
(m, n) if m.abs() < 2 && n.abs() < 2 => *tail,
2022-12-10 01:09:33 +00:00
_ => (tail.0 + dx.signum(), tail.1 + dy.signum()),
2022-12-09 23:49:09 +00:00
}
}