use alloc::vec::Vec;
use crate::graph::Vertex;
use crate::instance::AgentId;
use crate::path::{Time, position_at};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Conflict {
Vertex {
agents: (AgentId, AgentId),
vertex: Vertex,
time: Time,
},
Edge {
agents: (AgentId, AgentId),
from: Vertex,
to: Vertex,
time: Time,
},
}
impl Conflict {
#[must_use]
pub fn agents(&self) -> (AgentId, AgentId) {
match *self {
Self::Vertex { agents, .. } | Self::Edge { agents, .. } => agents,
}
}
#[must_use]
pub fn time(&self) -> Time {
match *self {
Self::Vertex { time, .. } | Self::Edge { time, .. } => time,
}
}
}
#[must_use]
pub fn first_conflict<P: AsRef<[Vertex]>>(paths: &[P]) -> Option<Conflict> {
let mut found = None;
scan(paths, |conflict| {
found = Some(conflict);
false
});
found
}
#[must_use]
pub fn conflicts<P: AsRef<[Vertex]>>(paths: &[P]) -> Vec<Conflict> {
let mut found = Vec::new();
scan(paths, |conflict| {
found.push(conflict);
true
});
found
}
fn scan<P: AsRef<[Vertex]>>(paths: &[P], mut visit: impl FnMut(Conflict) -> bool) {
let paths: Vec<&[Vertex]> = paths.iter().map(AsRef::as_ref).collect();
let horizon = paths.iter().map(|path| path.len()).max().unwrap_or(0);
let horizon = Time::try_from(horizon).expect("path lengths fit in u32 time steps");
for time in 0..horizon {
if !scan_time(&paths, time, &mut visit) {
return;
}
}
}
fn scan_time(paths: &[&[Vertex]], time: Time, visit: &mut impl FnMut(Conflict) -> bool) -> bool {
for (i, a) in paths.iter().enumerate() {
for (j, b) in paths.iter().enumerate().skip(i + 1) {
let pair = conflicts_at(a, b, (i, j), time);
if pair.into_iter().flatten().any(|conflict| !visit(conflict)) {
return false;
}
}
}
true
}
fn conflicts_at(
a: &[Vertex],
b: &[Vertex],
agents: (AgentId, AgentId),
time: Time,
) -> [Option<Conflict>; 2] {
let (a_now, b_now) = (position_at(a, time), position_at(b, time));
let (a_next, b_next) = (position_at(a, time + 1), position_at(b, time + 1));
let vertex = (a_now == b_now).then_some(Conflict::Vertex {
agents,
vertex: a_now,
time,
});
let swap = (a_now != a_next && a_now == b_next && a_next == b_now).then_some(Conflict::Edge {
agents,
from: a_now,
to: a_next,
time,
});
[vertex, swap]
}