use core::cmp::Ordering;
use search_core::{Cost, ExactArith, ExactNumber, Heuristic, WideMul};
use crate::bottleneck::{Bottleneck, minsum_maxmin};
use crate::graph::Graph;
use crate::output::Solution;
pub type WidePath<S, C> = Solution<S, (C, Bottleneck<C>)>;
pub fn min_cost_capacity_ratio<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
) -> Option<WidePath<G::State, C>>
where
G: Graph<Weight = (C, C)>,
H: Heuristic<G::State, C>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
let front = minsum_maxmin(graph, heuristic, start, is_goal).solutions;
front
.into_iter()
.min_by(|a, b| ratio_order(a.cost, b.cost).then(a.cost.0.cmp(&b.cost.0)))
}
fn ratio_order<C: Cost + WideMul>(a: (C, Bottleneck<C>), b: (C, Bottleneck<C>)) -> Ordering {
match (a.1, b.1) {
(None, None) => Ordering::Equal,
(None, Some(_)) => Ordering::Less,
(Some(_), None) => Ordering::Greater,
(Some(wa), Some(wb)) => a.0.wide_mul(wb).cmp(&b.0.wide_mul(wa)),
}
}
pub fn quickest_path<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
sigma: C,
) -> Option<WidePath<G::State, C>>
where
G: Graph<Weight = (C, C)>,
H: Heuristic<G::State, C>,
C: Cost + ExactArith,
P: Fn(&G::State) -> bool,
{
let front = minsum_maxmin(graph, heuristic, start, is_goal).solutions;
front
.into_iter()
.min_by(|a, b| time_order(a.cost, b.cost, sigma).then(a.cost.0.cmp(&b.cost.0)))
}
fn time_order<C: Cost + ExactArith>(
a: (C, Bottleneck<C>),
b: (C, Bottleneck<C>),
sigma: C,
) -> Ordering {
let infinite = |c: Bottleneck<C>| sigma > C::ZERO && c == Some(C::ZERO);
match (infinite(a.1), infinite(b.1)) {
(true, true) => return Ordering::Equal,
(true, false) => return Ordering::Greater,
(false, true) => return Ordering::Less,
(false, false) => {}
}
let time = |(d, c): (C, Bottleneck<C>)| match c.filter(|_| sigma > C::ZERO) {
None => (d.exact(), C::Exact::one()),
Some(c) => (d.exact() * c.exact() + sigma.exact(), c.exact()),
};
let ((na, da), (nb, db)) = (time(a), time(b));
(na * db).cmp(&(nb * da))
}
#[cfg(test)]
mod tests {
use core::cmp::Ordering;
use super::time_order;
#[test]
fn times_compare() {
assert_eq!(
time_order((1_u64, Some(1)), (10, Some(100)), 5),
Ordering::Less
);
assert_eq!(
time_order((1_u64, Some(1)), (10, Some(100)), 1000),
Ordering::Greater
);
assert_eq!(
time_order((0_u64, Some(0)), (1, None), 1),
Ordering::Greater
);
assert_eq!(
time_order((4_u64, Some(0)), (3, Some(7)), 0),
Ordering::Greater
);
let max = u128::MAX;
assert_eq!(
time_order((max, Some(max)), (max - 1, Some(max)), max),
Ordering::Greater
);
}
}