Skip to content

Commit cda40d9

Browse files
committed
perf: Optimise by only brute forcing scrapes on actual guard path
- reduced exectution time from 82 secs to 30 secs on local machine
1 parent 856100d commit cda40d9

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/day06.rs

+15-13
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
1-
use std::collections::HashMap;
1+
use std::collections::{HashMap, HashSet};
22

33
pub fn solve_part1(input: &str) -> i32 {
44
let map: Vec<Vec<char>> = parse_map(input);
5-
scrape_map_for_guard(map).0
5+
scrape_map_for_guard(&map).0
66
}
77

88
pub fn solve_part2(input: &str) -> i32 {
99
let map = parse_map(input);
10-
let mut map_variants: Vec<Vec<Vec<char>>> = vec![];
10+
let path_to_walk = scrape_map_for_guard(&map).1;
1111

12-
for (y, row) in map.iter().enumerate() {
13-
for (x, c) in row.iter().enumerate() {
14-
if *c != '^' || *c != 'v' || *c != '<' || *c != '>' {
15-
let mut map_variant = map.clone();
16-
map_variant[y][x] = '#';
17-
map_variants.push(map_variant);
18-
}
12+
let mut map_variants: Vec<Vec<Vec<char>>> = vec![];
13+
for (x, y) in path_to_walk {
14+
let c = map[y as usize][x as usize];
15+
if c != '^' || c != 'v' || c != '<' || c != '>' {
16+
let mut map_variant = map.clone();
17+
map_variant[y as usize][x as usize] = '#';
18+
map_variants.push(map_variant);
1919
}
2020
}
2121

2222
map_variants
2323
.iter()
24-
.filter(|map_variant| scrape_map_for_guard(map_variant.to_vec()).1)
24+
.filter(|map_variant| scrape_map_for_guard(&map_variant.to_vec()).2)
2525
.count() as i32
2626
}
2727

28-
fn scrape_map_for_guard(map: Vec<Vec<char>>) -> (i32, bool) {
28+
fn scrape_map_for_guard(map: &[Vec<char>]) -> (i32, HashSet<(i32, i32)>, bool) {
2929
let mut direction: Direction = Direction::Up;
3030
let mut position: (i32, i32) = (0, 0);
3131
let mut dist_positions: HashMap<(i32, i32), i32> = HashMap::new();
32+
let mut path_walked = HashSet::new();
3233
let mut infinite_loop = false;
3334

3435
for (y, row) in map.iter().enumerate() {
@@ -104,9 +105,10 @@ fn scrape_map_for_guard(map: Vec<Vec<char>>) -> (i32, bool) {
104105
}
105106

106107
position = new_position;
108+
path_walked.insert(position);
107109
}
108110

109-
((dist_positions.len() + 1) as i32, infinite_loop)
111+
((dist_positions.len() + 1) as i32, path_walked, infinite_loop)
110112
}
111113

112114
fn parse_map(input: &str) -> Vec<Vec<char>> {

0 commit comments

Comments
 (0)