1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#[cfg(test)]
#[path = "../../../tests/unit/models/solution/actor_test.rs"]
mod actor_test;
use crate::models::problem::{Actor, Fleet};
use crate::utils::Random;
use hashbrown::{HashMap, HashSet};
use std::sync::Arc;
pub struct Registry {
available: HashMap<usize, HashSet<Arc<Actor>>>,
index: HashMap<Arc<Actor>, usize>,
all: Vec<Arc<Actor>>,
random: Arc<dyn Random + Send + Sync>,
}
impl Registry {
pub fn new(fleet: &Fleet, random: Arc<dyn Random + Send + Sync>) -> Self {
let index = fleet
.groups
.iter()
.flat_map(|(group_id, actors)| actors.iter().map(|a| (a.clone(), *group_id)).collect::<Vec<_>>())
.collect();
Self { available: fleet.groups.clone(), index, all: fleet.actors.to_vec(), random }
}
pub fn use_actor(&mut self, actor: &Arc<Actor>) -> bool {
self.available.get_mut(self.index.get(actor).unwrap()).unwrap().remove(actor)
}
pub fn free_actor(&mut self, actor: &Arc<Actor>) -> bool {
self.available.get_mut(self.index.get(actor).unwrap()).unwrap().insert(actor.clone())
}
pub fn all<'a>(&'a self) -> impl Iterator<Item = Arc<Actor>> + 'a {
self.all.iter().cloned()
}
pub fn available<'a>(&'a self) -> impl Iterator<Item = Arc<Actor>> + 'a {
self.available.iter().flat_map(|(_, set)| set.iter().cloned())
}
pub fn next<'a>(&'a self) -> impl Iterator<Item = Arc<Actor>> + 'a {
let random = self.random.clone();
self.available.iter().flat_map(move |(_, set)| {
let skip_amount = if set.len() < 2 { 0 } else { random.uniform_int(0, set.len() as i32 - 1) as usize };
set.iter().skip(skip_amount).take(1).cloned()
})
}
pub fn deep_copy(&self) -> Self {
Self {
available: self.available.clone(),
index: self.index.clone(),
all: self.all.clone(),
random: self.random.clone(),
}
}
}