use alloc::vec::Vec;
use crate::graph::Vertex;
pub type Time = u32;
pub type Path = Vec<Vertex>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Objective {
SumOfCosts,
Makespan,
}
#[must_use]
pub fn position_at(path: &[Vertex], time: Time) -> Vertex {
let index = usize::try_from(time).unwrap_or(usize::MAX);
path.get(index)
.or(path.last())
.copied()
.expect("a path has at least one position")
}
#[must_use]
pub fn path_cost(path: &[Vertex]) -> u32 {
let Some(&last) = path.last() else {
return 0;
};
let trailing = path.iter().rev().take_while(|&&v| v == last).count();
let arrival = path.len() - trailing;
u32::try_from(arrival).expect("path lengths fit in u32 time steps")
}
#[must_use]
pub fn sum_of_costs<P: AsRef<[Vertex]>>(paths: &[P]) -> u32 {
paths.iter().map(|path| path_cost(path.as_ref())).sum()
}
#[must_use]
pub fn makespan<P: AsRef<[Vertex]>>(paths: &[P]) -> u32 {
paths
.iter()
.map(|path| path_cost(path.as_ref()))
.max()
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn cost_counts_until_final_arrival() {
assert_eq!(path_cost(&[3]), 0);
assert_eq!(path_cost(&[0, 1, 2]), 2);
assert_eq!(path_cost(&[0, 1, 1, 2, 2, 2]), 3);
assert_eq!(path_cost(&[2, 1, 2]), 2);
assert_eq!(sum_of_costs(&[vec![0, 1], vec![5, 5, 4]]), 3);
assert_eq!(makespan(&[vec![0, 1], vec![5, 5, 4]]), 2);
}
#[test]
fn position_stays_at_goal() {
assert_eq!(position_at(&[0, 1, 2], 1), 1);
assert_eq!(position_at(&[0, 1, 2], 10), 2);
}
}