From c22d4f14d791fa8488127d4c3e7d723aa81a71e9 Mon Sep 17 00:00:00 2001 From: Dan Johnson Date: Thu, 11 Sep 2025 13:19:44 -0700 Subject: [PATCH] Change A* heuristic to be a proper estimate This makes it: - Actually find the path with the fewest number of moves, and - Not be so prone to getting stuck exploring space that seems "close to a solution" but is actually a dead end. --- src/main.rs | 55 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/src/main.rs b/src/main.rs index d302c5e..7481c80 100644 --- a/src/main.rs +++ b/src/main.rs @@ -322,22 +322,8 @@ impl Game { hasher.finish() }; - #[derive(PartialEq)] - struct Ordf32(f32); - impl Eq for Ordf32 {} - impl PartialOrd for Ordf32 { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - impl Ord for Ordf32 { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.0.total_cmp(&other.0) - } - } - let mut states = Vec::new(); - let mut todo = BinaryHeap::<(Ordf32, usize, usize)>::new(); + let mut todo = BinaryHeap::<((i64, i64), i64, usize)>::new(); let mut had = HashSet::new(); let mut ctr = 0; @@ -346,7 +332,7 @@ impl Game { parent_index: 0, m: Move::new(0, 0), }); - todo.push((Ordf32(0.0), 1000000000, 0)); + todo.push(((0, 0), 1000000000, 0)); while let Some((score, depth, state_index)) = todo.pop() { ctr += 1; @@ -387,8 +373,36 @@ impl Game { working_instance.towers = state.towers.clone(); working_instance.make_move(m).unwrap(); - let num_solved = working_instance.num_solved(); - let brs = working_instance.burried_ring_score(); + let brs: i64 = { + let this = &working_instance; + let mut seen_bottom_rings = HashSet::new(); + this.towers + .iter() + .map(|i| { + let this = &i; + let mut ring_type = None; + let mut burried_score = 0; + + for ring in this.rings.iter().rev().flatten() { + if let Some(existing_ring_type) = ring_type + && existing_ring_type != *ring + { + burried_score += 1; + } + ring_type = Some(*ring); + } + if let Some(Some(ring)) = this.rings.last() { + if seen_bottom_rings.contains(ring) { + burried_score += 1; + } else { + seen_bottom_rings.insert(ring); + } + } + + burried_score + }) + .sum() + }; let new_state_hash = hash_state(&working_instance.towers); if had.contains(&new_state_hash) { @@ -402,9 +416,8 @@ impl Game { m, }); - let score = (num_solved as f32 * 10.0) + (-(brs as f32) * 100.0); - - todo.push((Ordf32(score), depth - 1, new_state_index)); + let score = (depth) - (brs); + todo.push(((score, -depth), depth - 1, new_state_index)); } } -- 2.50.1