Skip to main content

solverforge_solver/heuristic/selector/
list_swap.rs

1/* List swap move selector for element exchange.
2
3Generates `ListSwapMove`s that swap elements within or between list variables.
4Useful for inter-route rebalancing in vehicle routing problems.
5
6# Complexity
7
8For n entities with average route length m:
9- Intra-entity swaps: O(n * m * (m-1) / 2)
10- Inter-entity swaps: O(n² * m²)
11- Total: O(n² * m²) worst case (triangular optimization halves constant)
12
13# Example
14
15```
16use solverforge_solver::heuristic::selector::list_swap::ListSwapMoveSelector;
17use solverforge_solver::heuristic::selector::entity::FromSolutionEntitySelector;
18use solverforge_solver::heuristic::selector::MoveSelector;
19use solverforge_core::domain::PlanningSolution;
20use solverforge_core::score::SoftScore;
21
22#[derive(Clone, Debug)]
23struct Vehicle { visits: Vec<i32> }
24
25#[derive(Clone, Debug)]
26struct Solution { vehicles: Vec<Vehicle>, score: Option<SoftScore> }
27
28impl PlanningSolution for Solution {
29type Score = SoftScore;
30fn score(&self) -> Option<Self::Score> { self.score }
31fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
32}
33
34fn list_len(s: &Solution, entity_idx: usize) -> usize {
35s.vehicles.get(entity_idx).map_or(0, |v| v.visits.len())
36}
37fn list_get(s: &Solution, entity_idx: usize, pos: usize) -> Option<i32> {
38s.vehicles.get(entity_idx).and_then(|v| v.visits.get(pos).copied())
39}
40fn list_set(s: &mut Solution, entity_idx: usize, pos: usize, val: i32) {
41if let Some(v) = s.vehicles.get_mut(entity_idx) {
42if let Some(elem) = v.visits.get_mut(pos) { *elem = val; }
43}
44}
45
46let selector = ListSwapMoveSelector::<Solution, i32, _>::new(
47FromSolutionEntitySelector::new(0),
48list_len,
49list_get,
50list_set,
51"visits",
520,
53);
54```
55*/
56
57use std::fmt::Debug;
58use std::marker::PhantomData;
59
60use solverforge_core::domain::PlanningSolution;
61use solverforge_scoring::Director;
62
63use crate::heuristic::r#move::ListSwapMove;
64
65use super::entity::EntitySelector;
66use super::list_support::collect_selected_entities;
67use super::move_selector::{ArenaMoveCursor, MoveSelector};
68
69/// A move selector that generates list swap moves.
70///
71/// Enumerates all valid (entity_a, pos_a, entity_b, pos_b) pairs for swapping
72/// elements within or between list variables. Intra-entity swaps use a
73/// triangular iteration to avoid duplicate pairs.
74///
75/// # Type Parameters
76/// * `S` - The solution type
77/// * `V` - The list element type
78/// * `ES` - The entity selector type
79pub struct ListSwapMoveSelector<S, V, ES> {
80    entity_selector: ES,
81    list_len: fn(&S, usize) -> usize,
82    list_get: fn(&S, usize, usize) -> Option<V>,
83    list_set: fn(&mut S, usize, usize, V),
84    variable_name: &'static str,
85    descriptor_index: usize,
86    _phantom: PhantomData<(fn() -> S, fn() -> V)>,
87}
88
89impl<S, V: Debug, ES: Debug> Debug for ListSwapMoveSelector<S, V, ES> {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("ListSwapMoveSelector")
92            .field("entity_selector", &self.entity_selector)
93            .field("variable_name", &self.variable_name)
94            .field("descriptor_index", &self.descriptor_index)
95            .finish()
96    }
97}
98
99impl<S, V, ES> ListSwapMoveSelector<S, V, ES> {
100    /// Creates a new list swap move selector.
101    ///
102    /// # Arguments
103    /// * `entity_selector` - Selects entities to consider for swaps
104    /// * `list_len` - Function to get list length for an entity
105    /// * `list_get` - Function to get element at position
106    /// * `list_set` - Function to set element at position
107    /// * `variable_name` - Name of the list variable
108    /// * `descriptor_index` - Entity descriptor index
109    pub fn new(
110        entity_selector: ES,
111        list_len: fn(&S, usize) -> usize,
112        list_get: fn(&S, usize, usize) -> Option<V>,
113        list_set: fn(&mut S, usize, usize, V),
114        variable_name: &'static str,
115        descriptor_index: usize,
116    ) -> Self {
117        Self {
118            entity_selector,
119            list_len,
120            list_get,
121            list_set,
122            variable_name,
123            descriptor_index,
124            _phantom: PhantomData,
125        }
126    }
127}
128
129impl<S, V, ES> MoveSelector<S, ListSwapMove<S, V>> for ListSwapMoveSelector<S, V, ES>
130where
131    S: PlanningSolution,
132    V: Clone + PartialEq + Send + Sync + Debug + 'static,
133    ES: EntitySelector<S>,
134{
135    type Cursor<'a>
136        = ArenaMoveCursor<S, ListSwapMove<S, V>>
137    where
138        Self: 'a;
139
140    fn open_cursor<'a, D: Director<S>>(&'a self, score_director: &D) -> Self::Cursor<'a> {
141        let list_len = self.list_len;
142        let list_get = self.list_get;
143        let list_set = self.list_set;
144        let variable_name = self.variable_name;
145        let descriptor_index = self.descriptor_index;
146
147        let selected = collect_selected_entities(&self.entity_selector, score_director, list_len);
148        let move_capacity = selected.list_swap_move_capacity();
149        let entities = selected.entities;
150        let route_lens = selected.route_lens;
151
152        let mut moves = Vec::with_capacity(move_capacity);
153
154        for (i, &entity_a) in entities.iter().enumerate() {
155            let len_a = route_lens[i];
156            if len_a == 0 {
157                continue;
158            }
159
160            // Intra-entity swaps: triangular pairs (pos_a, pos_b) with pos_a < pos_b
161            for pos_a in 0..len_a {
162                for pos_b in pos_a + 1..len_a {
163                    moves.push(ListSwapMove::new(
164                        entity_a,
165                        pos_a,
166                        entity_a,
167                        pos_b,
168                        list_len,
169                        list_get,
170                        list_set,
171                        variable_name,
172                        descriptor_index,
173                    ));
174                }
175            }
176
177            // Inter-entity swaps: all pairs (entity_a, pos_a) x (entity_b, pos_b) where b > a
178            for (j, &entity_b) in entities.iter().enumerate() {
179                if j <= i {
180                    continue;
181                }
182                let len_b = route_lens[j];
183                if len_b == 0 {
184                    continue;
185                }
186
187                for pos_a in 0..len_a {
188                    for pos_b in 0..len_b {
189                        moves.push(ListSwapMove::new(
190                            entity_a,
191                            pos_a,
192                            entity_b,
193                            pos_b,
194                            list_len,
195                            list_get,
196                            list_set,
197                            variable_name,
198                            descriptor_index,
199                        ));
200                    }
201                }
202            }
203        }
204
205        ArenaMoveCursor::from_moves(moves)
206    }
207
208    fn size<D: Director<S>>(&self, score_director: &D) -> usize {
209        collect_selected_entities(&self.entity_selector, score_director, self.list_len)
210            .list_swap_move_capacity()
211    }
212}