From 164e731df01db40e90ea3774dfef5f821e67ac5b Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Fri, 9 Dec 2022 17:09:33 -0800 Subject: [PATCH] done with part2 --- 2022-aoc/src/d9.rs | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/2022-aoc/src/d9.rs b/2022-aoc/src/d9.rs index 41d42b3..de99082 100644 --- a/2022-aoc/src/d9.rs +++ b/2022-aoc/src/d9.rs @@ -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 { +fn parse_input(input: &str) -> Vec { 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 { } #[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()), } }