done with part2

This commit is contained in:
Joe Ardent 2022-12-09 17:09:33 -08:00
parent ca854d2cd3
commit 164e731df0

View file

@ -2,17 +2,16 @@ use std::collections::HashSet;
use aoc_runner_derive::{aoc as aoc_run, aoc_generator};
type Position = (i32, i32);
type Coord = (i32, i32);
#[aoc_generator(day9)]
fn parse_input(input: &str) -> Vec<Position> {
fn parse_input(input: &str) -> Vec<Coord> {
let mut out = Vec::new();
let (mut x, mut y) = (0, 0);
out.push((x, y));
for line in input.lines() {
let mut split = line.split_ascii_whitespace();
let dir = split.next().unwrap();
let num: i32 = split.next().unwrap().parse().unwrap();
let (dir, num) = line.split_once(' ').unwrap();
let num: i32 = num.parse().unwrap();
for _ in 0..num {
match dir {
"U" => y += 1,
@ -28,7 +27,7 @@ fn parse_input(input: &str) -> Vec<Position> {
}
#[aoc_run(day9, part1)]
fn part1(input: &[Position]) -> usize {
fn part1(input: &[Coord]) -> usize {
let mut tail = (0, 0);
let mut set = HashSet::new();
set.insert(tail);
@ -36,22 +35,30 @@ fn part1(input: &[Position]) -> usize {
tail = new_tail(mv, &tail);
set.insert(tail);
}
set.len()
}
#[aoc_run(day9, part2)]
fn part2(input: &[Position]) -> u32 {
0
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()
}
fn new_tail(head: &Position, tail: &Position) -> Position {
fn new_tail(head: &Coord, tail: &Coord) -> Coord {
let dy = head.1 - tail.1;
let dx = head.0 - tail.0;
match (dx, dy) {
(m, n) if m.abs() < 2 && n.abs() < 2 => *tail,
(m, _) if m.abs() == 2 => (tail.0 + m / 2, tail.1 + dy),
(_, m) if m.abs() == 2 => (tail.0 + dx, tail.1 + m / 2),
_ => unreachable!(),
_ => (tail.0 + dx.signum(), tail.1 + dy.signum()),
}
}