use crate::iw::iw_from;
use crate::{GoalCount, SearchResult};
pub fn siw<P: GoalCount>(problem: &P, max_k: usize) -> SearchResult<P::Action> {
let mut total = SearchResult {
plan: None,
expanded: 0,
generated: 0,
};
let mut state = problem.initial_state();
if problem.is_goal(&state) {
total.generated = 1;
}
let mut plan = Vec::new();
while !problem.is_goal(&state) {
let Some((subplan, next)) = reach_subgoal(problem, &state, max_k, &mut total) else {
return total;
};
plan.extend(subplan);
state = next;
}
total.plan = Some(plan);
total
}
fn reach_subgoal<P: GoalCount>(
problem: &P,
state: &P::State,
max_k: usize,
total: &mut SearchResult<P::Action>,
) -> Option<(Vec<P::Action>, P::State)> {
let g = problem.unsatisfied_goals(state);
let is_subgoal = |s: &P::State| problem.is_goal(s) || problem.unsatisfied_goals(s) < g;
for k in 1..=max_k {
let (r, end) = iw_from(problem, state.clone(), k, is_subgoal);
total.expanded += r.expanded;
total.generated += r.generated;
if let (Some(subplan), Some(end)) = (r.plan, end) {
return Some((subplan, end));
}
}
None
}