use alloc::collections::BTreeSet;
use alloc::vec::Vec;
use search_core::Cost;
use crate::cost::{Dominates, add};
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
pub fn brute_force<G, C, P, const N: usize>(
graph: &G,
start: G::State,
is_goal: P,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut enumeration = Enumeration {
graph,
is_goal,
path: Vec::new(),
on_path: BTreeSet::new(),
found: Vec::new(),
stats: Stats::default(),
};
enumeration.visit(start, [C::ZERO; N]);
Output {
solutions: non_dominated(enumeration.found),
stats: enumeration.stats,
}
}
struct Enumeration<'a, G: Graph, P, const N: usize> {
graph: &'a G,
is_goal: P,
path: Vec<G::State>,
on_path: BTreeSet<G::State>,
found: Vec<Solution<G::State, G::Weight>>,
stats: Stats,
}
impl<G, C, P, const N: usize> Enumeration<'_, G, P, N>
where
G: Graph<Weight = [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
fn visit(&mut self, state: G::State, cost: [C; N]) {
self.stats.expanded += 1;
self.path.push(state.clone());
if (self.is_goal)(&state) {
self.stats.generated += 1;
self.found.push(Solution {
cost,
path: self.path.clone(),
});
} else {
let mut successors = Vec::new();
self.graph.successors(&state, &mut successors);
self.on_path.insert(state);
for (next, weight) in successors {
if !self.on_path.contains(&next) {
self.visit(next, add(cost, weight));
}
}
}
if let Some(last) = self.path.pop() {
self.on_path.remove(&last);
}
}
}
fn non_dominated<S, C: Cost, const N: usize>(
found: Vec<Solution<S, [C; N]>>,
) -> Vec<Solution<S, [C; N]>> {
let costs: Vec<_> = found.iter().map(|s| s.cost).collect();
let mut kept: Vec<_> = found
.into_iter()
.filter(|s| !costs.iter().any(|c| c.dominates(&s.cost)))
.collect();
kept.sort_by_key(|s| s.cost);
kept.dedup_by_key(|s| s.cost);
kept
}