Skip to content

Commit

Permalink
day 16 optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 16, 2023
1 parent d021230 commit 9daf86a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.
| [Day 13](./src/bin/13.rs) | `12.3µs` | `15.9µs` |
| [Day 14](./src/bin/14.rs) | `25.0µs` | `4.5ms` |
| [Day 15](./src/bin/15.rs) | `20.4µs` | `85.9µs` |
| [Day 16](./src/bin/16.rs) | `1.6ms` | `87.7ms` |
| [Day 16](./src/bin/16.rs) | `965.6µs` | `48.7ms` |

**Total: 96.32ms**
**Total: 56.68ms**
<!--- benchmarking table --->

---
Expand Down
21 changes: 12 additions & 9 deletions src/bin/16.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,24 @@ pub fn part_two(input: &str) -> Option<u32> {
}

fn energize_count(grid: &Grid, start: Coordinate, start_dir: Direction) -> u32 {
let mut visited = HashSet::new();
let mut visited_coords = HashSet::new();
let mut energized = HashSet::new();
let mut queue = VecDeque::new();
visited.insert((start, start_dir));
visited_coords.insert(start);
energized.insert(start);
queue.push_back((start, start_dir));
while let Some((cur, dir)) = queue.pop_front() {
for (next, next_dir) in grid.neighbors(cur, dir) {
if visited.insert((next, next_dir)) {
visited_coords.insert(next);
queue.push_back((next, next_dir));
if let Some(tile) = grid.get_tile(next) {
match (tile, energized.insert(next)) {
// If we hit a splitter that was already energized, we know we are entering a loop so we can stop
(Tile::HorizontalSplitter, false) | (Tile::VerticalSplitter, false) => {}

// Otherwise keep going
_ => queue.push_back((next, next_dir)),
}
}
}
}
visited_coords.len() as u32
energized.len() as u32
}

struct Grid {
Expand Down Expand Up @@ -85,7 +88,7 @@ impl Grid {
.filter_map(move |dir| self.move_in_dir(coord, dir).map(|c| (c, dir)))
}

fn get_tile(&self, coord: Coordinate) -> Option<Tile> {
pub fn get_tile(&self, coord: Coordinate) -> Option<Tile> {
self.tiles
.get(coord.row)
.and_then(|row| row.get(coord.col))
Expand Down

0 comments on commit 9daf86a

Please sign in to comment.