Skip to content

Commit 2282c0c

Browse files
committed
perf(18/2024): optimize by pre-allocation memory for collections
1 parent 5165099 commit 2282c0c

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
| [Day 15: Warehouse Woes](src/solutions/year2024/day15.rs) | ⭐⭐ | 7.226 | 9.084 |
2929
| [Day 16: Reindeer Maze](src/solutions/year2024/day16.rs) || 6.478 | - |
3030
| [Day 17: Chronospatial Computer](src/solutions/year2024/day17.rs) | - | - | - |
31-
| [Day 18: RAM Run](src/solutions/year2024/day18.rs) | ⭐⭐ | 2.487 | 379.772 |
31+
| [Day 18: RAM Run](src/solutions/year2024/day18.rs) | ⭐⭐ | 2.487 | 204.885 |
3232
| [Day 19: Linen Layout](src/solutions/year2024/day19.rs) | ⭐⭐ | 2.923 | 22.751 |
3333

3434
# 2023

src/solutions/year2024/day18.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,16 @@ impl Solution for Day18 {
4545
let start = self.surface.top_left_corner();
4646
let end = self.surface.bottom_right_corner();
4747

48-
let mut skipped: HashSet<Point> = byte_positions
48+
let mut skipped = HashSet::with_capacity(byte_positions.len());
49+
50+
let new: HashSet<Point> = byte_positions
4951
.clone()
5052
.into_iter()
5153
.take(self.memory_size)
5254
.collect();
5355

56+
skipped.extend(new);
57+
5458
#[allow(clippy::needless_range_loop)]
5559
for i in self.memory_size..byte_positions.len() {
5660
let current = byte_positions[i];
@@ -80,8 +84,11 @@ impl Day18 {
8084
}
8185

8286
fn is_reachable(&self, blocked: &HashSet<Point>, start: Point, end: Point) -> bool {
83-
let mut visited = HashSet::new();
84-
let mut queue = vec![start];
87+
let mut visited = HashSet::with_capacity(self.surface.area());
88+
let mut queue = Vec::with_capacity(self.surface.area());
89+
90+
queue.push(start);
91+
visited.insert(start);
8592

8693
while let Some(current) = queue.pop() {
8794
if current == end {

0 commit comments

Comments
 (0)