From 53816fed73dcc0e787e93c7292fe1b918110c376 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 26 Dec 2024 11:16:18 -0800 Subject: [PATCH] day6, part2 --- day06/src/main.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/day06/src/main.rs b/day06/src/main.rs index ea993b9..f0f1e0b 100644 --- a/day06/src/main.rs +++ b/day06/src/main.rs @@ -29,13 +29,30 @@ fn pt2(input: &str) -> usize { let guard = board.guard; let no = [guard.0, guard.1.next(guard.0)]; + let mut trace = HashSet::new(); + while let Some((loc, _)) = board.step() { + if !no.contains(&loc) { + trace.insert(loc); + } + } - while let Some(loc) = board.step() {} + for loc in trace { + board = Board::new(input); + let mut steps = HashSet::new(); + board.set(loc, Cell::Obstacle); + steps.insert(board.guard); + while let Some(guard) = board.step() { + if !steps.insert(guard) { + total += 1; + break; + } + } + } total } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] enum Dir { #[default] N, @@ -127,6 +144,16 @@ impl Board { parse(input).unwrap() } + fn set(&mut self, loc: Loc, cell: Cell) -> bool { + if let Some(row) = self.cells.get_mut(loc.0) { + if let Some(c) = row.get_mut(loc.1) { + *c = cell; + return true; + } + } + false + } + fn step(&mut self) -> Option<(Loc, Dir)> { let (loc, dir) = &mut self.guard; *self