Skip to content

Commit 71ee2d3

Browse files
committed
positions optimization
1 parent dc05400 commit 71ee2d3

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/aoc2024/day6.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
use std::collections::HashSet;
2-
31
use crate::aoc2024::Aoc2024;
42
use crate::grid::Grid;
53
use crate::traits::days::Day6;
@@ -70,14 +68,15 @@ const DIRECTIONS: [(isize, isize); 4] = [(0, -1), (1, 0), (0, 1), (-1, 0)];
7068
fn compute_path_size(grid: &Grid<bool>, sx: usize, sy: usize) -> Option<usize> {
7169
let (mut x, mut y) = (sx, sy);
7270
let mut didx = 0;
73-
let mut positions = HashSet::new();
74-
let mut pos_and_dir = HashSet::new();
71+
let mut positions = Grid::new(grid.width, grid.height, [false; 4]);
7572

7673
loop {
77-
positions.insert((x, y));
78-
if !pos_and_dir.insert((x, y, didx)) {
74+
let pos = positions.get_mut(x, y);
75+
if pos[didx] {
7976
return None;
8077
}
78+
pos[didx] = true;
79+
8180
let (dx, dy) = DIRECTIONS[didx];
8281
if let Some((nx, ny)) = offset_pair(grid, x, y, dx, dy) {
8382
if *grid.get(nx, ny) {
@@ -91,9 +90,15 @@ fn compute_path_size(grid: &Grid<bool>, sx: usize, sy: usize) -> Option<usize> {
9190
}
9291
}
9392

94-
Some(positions.len())
93+
Some(
94+
positions
95+
.iter()
96+
.filter(|(_, _, &v)| v.into_iter().any(|b| b))
97+
.count(),
98+
)
9599
}
96100

101+
#[inline]
97102
fn offset_pair(
98103
grid: &Grid<bool>,
99104
x: usize,
@@ -110,6 +115,7 @@ fn offset_pair(
110115
}
111116
}
112117

118+
#[inline]
113119
fn offset(base: usize, offset: isize, max: usize) -> Option<usize> {
114120
let res = base as isize + offset;
115121

0 commit comments

Comments
 (0)