Tiny performance improvement by NOT borrowing coordinates when indexing the grid(?)

This commit is contained in:
2024-12-05 00:53:08 +01:00
parent 1b77234148
commit 20946c0549
2 changed files with 13 additions and 13 deletions

View File

@@ -13,11 +13,11 @@ impl Day4 {
Day4 { puzzle: Grid::parse(input, '.')}
}
fn check_with_step(&self, word: &str, i: usize, j: usize, step_x: isize, step_y: isize) -> bool {
let mut x = i;
let mut y = j;
fn check_with_step(&self, word: &str, start_x: usize, start_y: usize, step_x: isize, step_y: isize) -> bool {
let mut x = start_x;
let mut y = start_y;
for c in word.chars() {
if self.puzzle.get(&x, &y) == &c {
if self.puzzle.get(x, y) == &c {
x = x.wrapping_add_signed(step_x);
y = y.wrapping_add_signed(step_y);
} else {
@@ -35,7 +35,7 @@ impl DaySolver for Day4 {
let mut count = 0;
for i in 0..self.puzzle.width {
for j in 0..self.puzzle.height() {
if self.puzzle.get(&i, &j) == &'X' {
if self.puzzle.get(i, j) == &'X' {
// Horizontal & Vertical
if self.check_with_step("XMAS", i, j, 1, 0) { count += 1; }
if self.check_with_step("XMAS", i, j, 0, 1) { count += 1; }
@@ -56,7 +56,7 @@ impl DaySolver for Day4 {
let mut count = 0;
for i in 1..self.puzzle.width {
for j in 1..self.puzzle.height() {
if self.puzzle.get(&i, &j) == &'A' {
if self.puzzle.get(i, j) == &'A' {
// We search from the center, so:
if (self.check_with_step("MAS", i-1, j-1, 1, 1) ||
self.check_with_step("SAM", i-1, j-1, 1, 1)) &&

View File

@@ -36,12 +36,12 @@ impl<T: Clone + Sized> Grid<T> {
pub fn set_col(&mut self, x: usize, v: T) {
for y in 0..self.height() {
let idx = self.idx(&x, &y);
let idx = self.idx(x, y);
self.data[idx] = v.to_owned();
}
}
pub(crate) fn idx(&self, x: &usize, y: &usize) -> usize {
pub(crate) fn idx(&self, x: usize, y: usize) -> usize {
y * self.width + x
}
@@ -53,7 +53,7 @@ impl<T: Clone + Sized> Grid<T> {
self.data.len() / self.width
}
pub(crate) fn get(&self, x: &usize, y: &usize) -> &T {
pub(crate) fn get(&self, x: usize, y: usize) -> &T {
if self.in_bounds(x, y) {
let idx = self.idx(x, y);
&self.data[idx]
@@ -64,13 +64,13 @@ impl<T: Clone + Sized> Grid<T> {
}
}
pub fn set(&mut self, x: &usize, y: &usize, v: T) {
pub fn set(&mut self, x: usize, y: usize, v: T) {
let idx = self.idx(x, y);
self.data[idx] = v;
}
pub fn in_bounds(&self, x: &usize, y: &usize) -> bool {
x < &self.width && y < &self.height()
pub fn in_bounds(&self, x: usize, y: usize) -> bool {
x < self.width && y < self.height()
}
pub fn find_positions<'a, P>(&'a self, predicate: &'a P) -> impl Iterator<Item = Coord<usize>> + 'a
@@ -99,7 +99,7 @@ impl <T: Display + Clone + Sized> Grid<T> {
for y in from_y.max(0)..to_y.min(self.height()) {
for x in from_x.max(0)..to_x.min(self.width) {
print!("{}", self.get(&x, &y))
print!("{}", self.get(x, y))
}
println!();
}