use alloc::vec::Vec;
use core::fmt;
use super::Valuation;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Violation<Task> {
pub path: Vec<Task>,
pub added: Task,
pub task: Task,
pub before: Option<u64>,
pub after: Option<u64>,
}
impl<Task: fmt::Debug> fmt::Display for Violation<Task> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"adding {:?} to path {:?} raised the gain of {:?} from {:?} to {:?}",
self.added, self.path, self.task, self.before, self.after
)
}
}
impl<Task: fmt::Debug> core::error::Error for Violation<Task> {}
pub fn check_diminishing<Task, V>(
valuation: &V,
tasks: &[Task],
capacity: usize,
) -> Result<(), Violation<Task>>
where
Task: Clone,
V: Valuation<Task> + ?Sized,
{
let mut search = Search {
valuation,
tasks,
capacity,
path: Vec::new(),
used: alloc::vec![false; tasks.len()],
};
search.explore()
}
struct Search<'a, Task, V: ?Sized> {
valuation: &'a V,
tasks: &'a [Task],
capacity: usize,
path: Vec<Task>,
used: Vec<bool>,
}
impl<Task, V> Search<'_, Task, V>
where
Task: Clone,
V: Valuation<Task> + ?Sized,
{
fn explore(&mut self) -> Result<(), Violation<Task>> {
if self.path.len() >= self.capacity {
return Ok(());
}
for added in 0..self.tasks.len() {
if self.used[added] {
continue;
}
let Some(insertion) = self
.valuation
.best_insertion(&self.path, &self.tasks[added])
else {
continue;
};
let mut extended = self.path.clone();
extended.insert(insertion.position, self.tasks[added].clone());
if extended.len() < self.capacity {
self.check_extension(added, &extended)?;
}
self.descend(added, extended)?;
}
Ok(())
}
fn check_extension(&self, added: usize, extended: &[Task]) -> Result<(), Violation<Task>> {
for task in 0..self.tasks.len() {
if task == added || self.used[task] {
continue;
}
let before = self.valuation.marginal_score(&self.path, &self.tasks[task]);
let after = self.valuation.marginal_score(extended, &self.tasks[task]);
if after > before {
return Err(Violation {
path: self.path.clone(),
added: self.tasks[added].clone(),
task: self.tasks[task].clone(),
before,
after,
});
}
}
Ok(())
}
fn descend(&mut self, added: usize, extended: Vec<Task>) -> Result<(), Violation<Task>> {
let previous = core::mem::replace(&mut self.path, extended);
self.used[added] = true;
let result = self.explore();
self.used[added] = false;
self.path = previous;
result
}
}