pub struct WeightedGraph<const SIZE: usize, T: Copy = f32> {
data: [[Option<T>; SIZE]; SIZE],
}
impl<const SIZE: usize, T: Copy> WeightedGraph<SIZE, T> {
pub const fn add_edge(
&mut self,
i: usize,
j: usize,
weight: T,
) {
self.data[i][j] = Some(weight);
}
pub const fn add_edge_undirected(
&mut self,
i: usize,
j: usize,
weight: T,
) {
self.data[i][j] = Some(weight);
self.data[j][i] = Some(weight);
}
pub const fn remove_edge(&mut self, i: usize, j: usize) {
self.data[i][j] = None;
}
pub const fn remove_edge_undirected(
&mut self,
i: usize,
j: usize,
) {
self.data[i][j] = None;
self.data[j][i] = None;
}
pub const fn get_edge(
&self,
i: usize,
j: usize,
) -> Option<T> {
self.data[i][j]
}
pub const fn has_edge(&self, i: usize, j: usize) -> bool {
self.data[i][j].is_some()
}
pub const fn get_edges(
&self,
vertex: usize,
) -> &[Option<T>; SIZE] {
&self.data[vertex]
}
pub const fn get_inverse_edges(
&self,
vertex: usize,
) -> [Option<T>; SIZE] {
let mut edges = [None; SIZE];
let mut neighbor = 0;
while neighbor < SIZE {
edges[neighbor] = self.data[neighbor][vertex];
neighbor += 1;
}
edges
}
pub const fn max_number_of_edges(&self) -> usize {
SIZE * (SIZE - 1)
}
pub const fn density(&self) -> f32 {
let mut edges = 0;
let mut i = 0;
while i < SIZE {
let mut j = 0;
while j < SIZE {
if self.data[i][j].is_some() {
edges += 1;
}
j += 1;
}
i += 1;
}
edges as f32 / self.max_number_of_edges() as f32
}
pub const fn clear(&mut self) {
let mut i = 0;
while i < SIZE {
let mut j = 0;
while j < SIZE {
self.data[i][j] = None;
j += 1;
}
i += 1;
}
}
pub const fn new() -> WeightedGraph<SIZE, T> {
WeightedGraph {
data: [[None; SIZE]; SIZE],
}
}
}