Skip to main content

search_core/cost/
lexicographic.rs

1//! The pair cost [`Lexicographic`]: a primary cost with a secondary tie-breaker.
2
3use core::ops::Add;
4
5use super::Cost;
6
7/// A path cost ordered by [`primary`](Self::primary) first, with ties broken by
8/// [`secondary`](Self::secondary). Both components add up along a path.
9///
10/// Use it to break ties between equally cheap paths by a second criterion, such as the
11/// fewest steps and then the fewest turns, or the cheapest route and then the fewest
12/// conflicts with other agents. Any search generic over [`Cost`] accepts it unchanged.
13///
14/// # Heuristics
15///
16/// A heuristic `(h, S::ZERO)`, where `h` is admissible or consistent for the primary cost,
17/// keeps that property for the pair: `(h(u), 0) <= (c + h(v), s)` whenever
18/// `h(u) <= c + h(v)`. A* then returns a path of minimal primary cost and, among those, of
19/// minimal secondary cost.
20///
21/// # Overflow
22///
23/// `+` adds component-wise and overflows like its components. [`Cost::saturating_add`] and
24/// [`Cost::saturating_times`] saturate each component separately.
25///
26/// # Examples
27///
28/// ```
29/// use search_core::{Cost, Lexicographic};
30///
31/// let fast = Lexicographic::new(10_u32, 3_u32);
32/// let calm = Lexicographic::new(10_u32, 1_u32);
33/// let slow = Lexicographic::new(11_u32, 0_u32);
34///
35/// assert!(calm < fast); // Same primary cost: fewer conflicts win.
36/// assert!(fast < slow); // The primary cost always decides first.
37/// assert_eq!(fast + calm, Lexicographic::new(20, 4));
38/// assert_eq!(Lexicographic::<u32, u32>::ZERO, Lexicographic::new(0, 0));
39/// ```
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct Lexicographic<P, S> {
42    /// The cost that is minimized first.
43    pub primary: P,
44    /// The tie-breaker, compared only between equal primary costs.
45    pub secondary: S,
46}
47
48impl<P, S> Lexicographic<P, S> {
49    /// Creates the cost `(primary, secondary)`.
50    #[must_use]
51    pub const fn new(primary: P, secondary: S) -> Self {
52        Self { primary, secondary }
53    }
54}
55
56impl<P: Add<Output = P>, S: Add<Output = S>> Add for Lexicographic<P, S> {
57    type Output = Self;
58
59    /// Adds component-wise.
60    fn add(self, other: Self) -> Self {
61        Self::new(
62            self.primary + other.primary,
63            self.secondary + other.secondary,
64        )
65    }
66}
67
68impl<P: Cost, S: Cost> Cost for Lexicographic<P, S> {
69    const ZERO: Self = Self::new(P::ZERO, S::ZERO);
70
71    /// Adds component-wise, each component saturating on its own.
72    fn saturating_add(self, other: Self) -> Self {
73        Self::new(
74            self.primary.saturating_add(other.primary),
75            self.secondary.saturating_add(other.secondary),
76        )
77    }
78
79    /// Scales component-wise, each component saturating on its own.
80    fn saturating_times(self, factor: u32) -> Self {
81        Self::new(
82            self.primary.saturating_times(factor),
83            self.secondary.saturating_times(factor),
84        )
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    //! Unit and property tests for [`Lexicographic`].
91
92    use proptest::prelude::*;
93
94    use super::{Cost, Lexicographic};
95    use crate::Decimal;
96
97    /// Builds a `u32` pair cost.
98    fn cost(primary: u32, secondary: u32) -> Lexicographic<u32, u32> {
99        Lexicographic::new(primary, secondary)
100    }
101
102    /// The primary cost decides; the secondary only breaks ties.
103    #[test]
104    fn orders_lexicographically() {
105        assert!(cost(1, 9) < cost(2, 0));
106        assert!(cost(2, 0) < cost(2, 1));
107        assert_eq!(cost(3, 3).max(cost(3, 4)), cost(3, 4));
108    }
109
110    /// The saturating operations saturate each component on its own.
111    #[test]
112    fn saturates_per_component() {
113        assert_eq!(
114            cost(u32::MAX, 1).saturating_add(cost(1, 1)),
115            cost(u32::MAX, 2)
116        );
117        assert_eq!(cost(u32::MAX, 2).saturating_times(2), cost(u32::MAX, 4));
118        assert_eq!(cost(5, 7).saturating_times(0), Lexicographic::ZERO);
119    }
120
121    /// The components may be different cost types.
122    #[test]
123    fn mixes_cost_types() {
124        let a = Lexicographic::new(Decimal::<2>::from_raw(150), 1_u8);
125        let b = Lexicographic::new(Decimal::<2>::from_raw(150), 0_u8);
126
127        assert!(b < a);
128        assert_eq!((a + b).primary, Decimal::from_raw(300));
129    }
130
131    proptest! {
132        /// The order is the order of `(primary, secondary)` tuples.
133        #[test]
134        fn matches_tuple_order(a: (u32, u32), b: (u32, u32)) {
135            prop_assert_eq!(cost(a.0, a.1).cmp(&cost(b.0, b.1)), a.cmp(&b));
136        }
137
138        /// A heuristic `(h, 0)` that is consistent for the primary cost stays consistent.
139        #[test]
140        fn zero_secondary_heuristic_stays_consistent(
141            h_u in 0..1_000_u32, c in 0..1_000_u32, h_v in 0..1_000_u32, s: u16,
142        ) {
143            prop_assume!(h_u <= c + h_v);
144            prop_assert!(cost(h_u, 0) <= cost(c, u32::from(s)) + cost(h_v, 0));
145        }
146    }
147}