From ea761135bb8002049b4bb001402e3b1749b80494 Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Sun, 28 Jan 2024 00:03:40 +0100 Subject: [PATCH] failed attempt at A* pathfinding, no clue --- src/day17/mod.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/day17/mod.rs b/src/day17/mod.rs index 08cd667..2f3a85c 100644 --- a/src/day17/mod.rs +++ b/src/day17/mod.rs @@ -9,11 +9,78 @@ pub fn part_one() { } fn pathfind(grid: &mut Vec>) -> i32 { + let mut closed: Vec<&mut Block> = Vec::new(); + let (end, mut open); + { + let result = init_pos(grid); + end = result.0; + open = result.1; + }; + + while !open.is_empty() { + let mut current = None; + let mut index = 0; + let mut record = std::i32::MAX; + + // Get best distance + heuristic + for (i, next) in open.iter().enumerate() { + let score = next.d + next.h; + if score < record { + record = score; + index = i; + } + } + + // Remove current from open set + current = Some(open.remove(index)); + + if let Some(current) = current { + // Break if current is end + if current.compare(end) { + break; + } + + // Scan neighbors, limit straight line length + // Add neighbors to open set + for (j, line) in grid.iter_mut().enumerate() { + for (i, next) in line.iter_mut().enumerate() { + if !closed.contains(&next) && !open.contains(&next) { + next.d = current.d + next.c; + next.h = next.distance(end); + open.push(next); + } + } + } + + // Add current to closed set + closed.push(current); + } + } + + end.d +} + +fn init_pos(grid: &mut Vec>) -> (&mut Block, Vec<&mut Block>) { + let mut open = Vec::new(); + + let middle = grid.len() / 2; + let (top, bottom) = grid.split_at_mut(middle); + + let start = top.first_mut().unwrap().first_mut().unwrap(); + let end = bottom.last_mut().unwrap().last_mut().unwrap(); + + start.h = start.distance(end) as i32; + open.push(start); + + (end, open) } struct Block { x: usize, y: usize, + c: i32, + d: i32, + h: i32, } impl Block { @@ -28,6 +95,14 @@ impl Block { } } +impl PartialEq for Block { + fn eq(&self, other: &Self) -> bool { + self.compare(other) + } +} + +impl Eq for Block {} + fn setup() -> Vec> { let name = "day17"; println!("Executing module '{name}' entrypoint . . . ");