day6: performance - only check obstacles on the original path

700ms -> 150ms
This commit is contained in:
Keenan Tims 2024-12-06 10:59:43 -08:00
parent 1cd535c2aa
commit b1918bbebf
Signed by: ktims
GPG Key ID: 11230674D69038D4

View File

@ -216,21 +216,25 @@ fn problem1<T: BufRead>(input: Lines<T>) -> u64 {
// PROBLEM 2 solution // PROBLEM 2 solution
fn problem2<T: BufRead>(input: Lines<T>) -> u64 { fn problem2<T: BufRead>(input: Lines<T>) -> u64 {
let input_map = Map::from(input); let input_map = Map::from(input);
// Use the solution from problem 1 to reduce the number of positions where obstacle placement will change the path
let mut part1 = input_map.clone();
part1.run_guard();
let mut loop_count = 0u64; let mut loop_count = 0u64;
for y in 0..input_map.grid.height() { for pos in part1
for x in 0..input_map.grid.width() { .grid
match input_map.grid.get(x as i64, y as i64) { .data
Some(b'.') => { .iter()
let mut test_map = input_map.clone(); .enumerate()
test_map.grid.set(x as i64, y as i64, b'#'); .filter_map(|(pos, c)| if *c == b'X' { Some(pos) } else { None })
if let RunOutcome::LoopFound = test_map.run_guard() { {
loop_count += 1 let mut test_map = input_map.clone();
} test_map.grid.data[pos] = b'#';
} if let RunOutcome::LoopFound = test_map.run_guard() {
_ => continue, loop_count += 1
}
} }
} }
loop_count loop_count
} }