From 9de4d77a637844a48f374a4d669bdfb461b0ba40 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Fri, 5 Dec 2025 01:25:14 -0500 Subject: [PATCH] Improve perf of day 4 --- README.md | 2 +- src/day04/mod.rs | 38 +++++++++++++++++++++----------------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 0268250..e30d754 100644 --- a/README.md +++ b/README.md @@ -35,4 +35,4 @@ Timings are given as: [lower-bound **best-estimate** upper-bound] | 01 | [101.34 µs **101.95 µs** 102.61 µs] | [105.90 µs **106.40 µs** 106.95 µs] | | 02 | [2.0990 ms **2.1113 ms** 2.1236 ms] | [2.0954 ms **2.1055 ms** 2.1157 ms] | | 03 | [38.717 µs **39.002 µs** 39.311 µs] | [175.35 µs **176.59 µs** 177.92 µs] | -| 04 | [233.55 µs **234.88 µs** 236.20 µs] | [3.1026 ms **3.1174 ms** 3.1326 ms] | +| 04 | [147.02 µs **147.75 µs** 148.53 µs] | [1.5579 ms **1.5737 ms** 1.5900 ms] | diff --git a/src/day04/mod.rs b/src/day04/mod.rs index 3d375fc..1d0a56f 100644 --- a/src/day04/mod.rs +++ b/src/day04/mod.rs @@ -8,6 +8,17 @@ use tracing::{debug, instrument}; pub const INPUT: &str = include_str!("input/input.txt"); +const ADJACENT_DELTAS: [(isize, isize); 8] = [ + (-1, -1), + (-1, 0), + (-1, 1), + (0, -1), + (0, 1), + (1, -1), + (1, 0), + (1, 1), +]; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Cell { Empty, @@ -77,14 +88,6 @@ impl Display for Grid { } impl Grid { - fn get_cell(&self, row: isize, col: isize) -> Option { - if row >= 0 && col >= 0 && (row as usize) < R && (col as usize) < C { - Some(self.cells[row as usize][col as usize]) - } else { - None - } - } - fn count_accessible_papers(&mut self, replace_with: Cell) -> usize { let mut count = 0; for row in 0..R { @@ -93,15 +96,16 @@ impl Grid { continue; } let mut adjacent_papers = 0; - for dr in -1..=1 { - for dc in -1..=1 { - if dr == 0 && dc == 0 { - continue; - } - let adjacent = self - .get_cell(row as isize + dr, col as isize + dc) - .unwrap_or(Cell::Empty); - if adjacent == Cell::Paper || adjacent == Cell::AccessiblePaper { + for &(dr, dc) in &ADJACENT_DELTAS { + let adj_row = row as isize + dr; + let adj_col = col as isize + dc; + if adj_row >= 0 + && adj_col >= 0 + && (adj_row as usize) < R + && (adj_col as usize) < C + { + let adjacent = self.cells[adj_row as usize][adj_col as usize]; + if matches!(adjacent, Cell::Paper | Cell::AccessiblePaper) { adjacent_papers += 1; } }