day18: improve brute for for binary search for big gainz
All checks were successful
test / AoC 2024 (push) Successful in 1m48s

also avoid unnecessary path tracking work
This commit is contained in:
Keenan Tims 2024-12-18 11:33:26 -08:00
parent 1c254fff93
commit 2a11e17d92
Signed by: ktims
GPG Key ID: 11230674D69038D4

View File

@ -10,6 +10,7 @@ struct MemoryMap {
} }
trait PathTrack { trait PathTrack {
const DOES_WORK: bool = true;
fn new() -> Self; fn new() -> Self;
fn push(&mut self, pos: (i64, i64)); fn push(&mut self, pos: (i64, i64));
fn finalize(&mut self) {} fn finalize(&mut self) {}
@ -37,6 +38,15 @@ impl PathTrack for Vec<(i64, i64)> {
} }
} }
struct NoopTrack {}
impl PathTrack for NoopTrack {
const DOES_WORK: bool = false;
fn new() -> Self {
Self {}
}
fn push(&mut self, _: (i64, i64)) {}
}
impl MemoryMap { impl MemoryMap {
fn from_str(input: &str, width: usize, height: usize) -> Self { fn from_str(input: &str, width: usize, height: usize) -> Self {
let map = Grid::with_shape(width, height, true); let map = Grid::with_shape(width, height, true);
@ -51,17 +61,14 @@ impl MemoryMap {
Self { map, byte_stream } Self { map, byte_stream }
} }
// Return if the byte caused a new blockage or not
fn place_byte(&mut self, i: usize) -> bool { fn place_byte(&mut self, i: usize) {
let pos = self.byte_stream[i]; let pos = self.byte_stream[i];
match self.map.set(&pos, false) { self.map.set(&pos, false);
None => panic!("corruption outside memory bounds"),
Some(x) => x,
} }
}
fn place_bytes(&mut self, n: usize) { fn place_bytes(&mut self, start: usize, end: usize) {
assert!(n < self.byte_stream.len()); for i in start..=end {
for i in 0..n {
self.place_byte(i); self.place_byte(i);
} }
} }
@ -85,6 +92,7 @@ impl MemoryMap {
while let Some((cost, pos)) = queue.pop() { while let Some((cost, pos)) = queue.pop() {
if pos == goal { if pos == goal {
if T::DOES_WORK {
let mut visited_pos = goal; let mut visited_pos = goal;
let mut path = T::new(); let mut path = T::new();
path.push(pos); path.push(pos);
@ -96,6 +104,9 @@ impl MemoryMap {
return Some(path); return Some(path);
} }
} }
} else {
return Some(T::new());
}
} }
if costs.get(&pos).is_some_and(|v| cost.0 > *v) { if costs.get(&pos).is_some_and(|v| cost.0 > *v) {
@ -106,7 +117,9 @@ impl MemoryMap {
for new_pos in moves { for new_pos in moves {
if costs.get(&new_pos).is_none_or(|best_cost| cost.0 + 1 < *best_cost) { if costs.get(&new_pos).is_none_or(|best_cost| cost.0 + 1 < *best_cost) {
costs.set(&new_pos, cost.0 + 1); costs.set(&new_pos, cost.0 + 1);
if T::DOES_WORK {
prev.set(&new_pos, pos); prev.set(&new_pos, pos);
}
queue.push((Reverse(cost.0 + 1), new_pos)); queue.push((Reverse(cost.0 + 1), new_pos));
} }
} }
@ -115,23 +128,24 @@ impl MemoryMap {
} }
} }
pub fn part1_impl(input: &str, width: usize, height: usize, n: usize) -> usize { pub fn part1_impl(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> usize {
let mut map = MemoryMap::from_str(input, width, height); let mut map = MemoryMap::from_str(input, width, height);
map.place_bytes(n); map.place_bytes(0, initial_safe_byte_count - 1);
let path = map.dijkstra::<LengthPath>((0, 0)).expect("no path found"); let path = map.dijkstra::<LengthPath>((0, 0)).expect("no path found");
path.0 - 1 // count edges, not visited nodes (start doesn't count) path.0 - 1 // count edges, not visited nodes (start doesn't count)
} }
pub fn part2_impl(input: &str, width: usize, height: usize, n: usize) -> (i64, i64) { // My original devised solution
pub fn part2_impl_brute(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> (i64, i64) {
let mut input_map = MemoryMap::from_str(input, width, height); let mut input_map = MemoryMap::from_str(input, width, height);
input_map.place_bytes(0, initial_safe_byte_count - 1);
input_map.place_bytes(n);
let mut path = input_map.dijkstra::<Vec<(i64, i64)>>((0, 0)).expect("no path found"); let mut path = input_map.dijkstra::<Vec<(i64, i64)>>((0, 0)).expect("no path found");
for byte in n..input_map.byte_stream.len() { for byte in initial_safe_byte_count..input_map.byte_stream.len() {
if input_map.place_byte(byte) { input_map.place_byte(byte);
// If it's a new blockage, and it obstructs our best path, we need to do a new path search // If it obstructs our best path, we need to do a new path search
if let Some((obs_at, _)) = path.iter().find_position(|v| *v == &input_map.byte_stream[byte]) { if let Some((obs_at, _)) = path.iter().find_position(|v| *v == &input_map.byte_stream[byte]) {
let (before, _) = path.split_at(obs_at); let (before, _) = path.split_at(obs_at);
@ -142,10 +156,28 @@ pub fn part2_impl(input: &str, width: usize, height: usize, n: usize) -> (i64, i
} }
} }
} }
}
panic!("no bytes block route"); panic!("no bytes block route");
} }
// Optimized based on others' ideas
pub fn part2_impl(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> (i64, i64) {
let mut input_map = MemoryMap::from_str(input, width, height);
input_map.place_bytes(0, initial_safe_byte_count - 1);
// for the unplaced bytes, binary search for the partition point, given the predicate that a path is reachable
// when all bytes up to that n have been placed
let possible_problems = (initial_safe_byte_count..input_map.byte_stream.len()).collect_vec();
let solution = possible_problems.partition_point(|byte| {
// avoiding this clone by rolling back the byte placements instead is slower
let mut local_map = input_map.clone();
local_map.place_bytes(initial_safe_byte_count, *byte);
local_map.dijkstra::<NoopTrack>((0, 0)).is_some()
}) + initial_safe_byte_count;
return input_map.byte_stream[solution];
}
#[aoc(day18, part1)] #[aoc(day18, part1)]
pub fn part1(input: &str) -> usize { pub fn part1(input: &str) -> usize {
part1_impl(input, 71, 71, 1024) part1_impl(input, 71, 71, 1024)
@ -195,4 +227,9 @@ mod tests {
fn part2_example() { fn part2_example() {
assert_eq!(part2_impl(EXAMPLE, 7, 7, 12), (6, 1)); assert_eq!(part2_impl(EXAMPLE, 7, 7, 12), (6, 1));
} }
#[test]
fn part2_example_brute() {
assert_eq!(part2_impl_brute(EXAMPLE, 7, 7, 12,), (6, 1));
}
} }