Skip to content

Commit

Permalink
optimize day 21 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
dcastil committed Jan 22, 2024
1 parent 44687c9 commit a4a83da
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 29 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.
| [Day 18](./src/bin/18.rs) | `5.0ms` | `41.7µs` |
| [Day 19](./src/bin/19.rs) | `239.3µs` | `265.0µs` |
| [Day 20](./src/bin/20.rs) | `1.8ms` | `8.1ms` |
| [Day 21](./src/bin/21.rs) | `10.3ms` | `2.5ms` |
| [Day 21](./src/bin/21.rs) | `2.4ms` | `2.6ms` |

**Total: 1988.52ms**
**Total: 1980.72ms**

<!--- benchmarking table --->

Expand Down
35 changes: 8 additions & 27 deletions src/bin/21.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,15 @@ pub fn part_one(input: &str) -> Option<usize> {

fn part_one_with_step_count(input: &str, step_count: u8) -> Option<usize> {
let garden = Garden::from_input(input);
let positions = garden.get_possible_positions(step_count);
let distance_map = garden.get_distance_map();
let step_count_modulo = step_count % 2;

Some(positions.len())
Some(
distance_map
.values()
.filter(|&&v| v <= step_count && v % 2 == step_count_modulo)
.count(),
)
}

// Solution from https://github.com/villuna/aoc23/wiki/A-Geometric-solution-to-advent-of-code-2023,-day-21
Expand Down Expand Up @@ -95,31 +101,6 @@ impl Garden {
}
}

fn get_possible_positions(&self, step_count: u8) -> HashSet<Coordinate> {
let mut positions = HashSet::from([self.start.clone()]);

for _ in 0..step_count {
let mut next_positions = HashSet::new();

for coordinate in positions {
next_positions.extend(
[
Direction::Up,
Direction::Down,
Direction::Left,
Direction::Right,
]
.iter()
.filter_map(|direction| self.get_next_coordinate(&coordinate, direction)),
);
}

positions = next_positions;
}

positions
}

fn get_distance_map(&self) -> HashMap<Coordinate, u8> {
let mut distance_map = HashMap::new();

Expand Down

0 comments on commit a4a83da

Please sign in to comment.