still broken !

This commit is contained in:
jacekpoz 2024-06-22 18:23:04 +02:00
parent 9c9b46d31d
commit 6f1a45c954
Signed by: poz
SSH key fingerprint: SHA256:JyLeVWE4bF3tDnFeUpUaJsPsNlJyBldDGV/dIKSLyN8

View file

@ -42,19 +42,24 @@ impl Ord for Edge {
pub struct Graph { pub struct Graph {
pub size: usize, pub size: usize,
pub edges: Vec<Edge>, pub edges: Vec<Vec<f64>>,
} }
impl Graph { impl Graph {
pub fn new(size: usize) -> Self { pub fn new(size: usize) -> Self {
Self { Self {
size, size,
edges: (0..size).map(|u| // edges: (0..size).map(|u|
(0..size).map(|v| // (0..size).map(|v|
Edge { src: u, dst: v, weight: 0.0 } // Edge { src: u, dst: v, weight: 0.0 }
).collect::<Vec<_>>() // ).collect::<Vec<_>>()
).flatten() // ).flatten()
.collect::<Vec<_>>(), // .collect::<Vec<_>>(),
edges: (0..size)
.map(|_| (0..size)
.map(|_| 0.0)
.collect::<Vec<_>>())
.collect::<Vec<_>>(),
} }
} }
@ -63,112 +68,71 @@ impl Graph {
size, size,
edges: (0..size).map(|u| edges: (0..size).map(|u|
(0..size).map(|v| (0..size).map(|v|
Edge { if u == v { 0.0 }
src: u, else { thread_rng().gen::<f64>() }
dst: v, ).collect::<Vec<_>>())
weight: if u == v { 0.0 }
else { thread_rng().gen::<f64>() }
}
).collect::<Vec<_>>()
).flatten()
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
} }
} }
pub fn vertex(&self, u: usize, v: usize) -> Option<f64> { pub fn edges(&self) -> Vec<Edge> {
if u >= self.size || v >= self.size { (0..self.size)
return None; .map(|i|
} (0..self.size)
.map(|j| Edge {
Some(self.edges.iter().find(|e| e.src == u && e.dst == v).unwrap().weight) src: i,
dst: j,
weight: self.edges[i][j],
})
.collect::<Vec<_>>()
)
.flatten()
.collect::<Vec<_>>()
} }
pub fn prim(&self) -> Vec<Edge> { pub fn prim(&self) -> Vec<Edge> {
// Associate with each vertex v of the graph a number C[v] (the cheapest cost of a connection to v) and an edge E[v] (the edge providing that cheapest connection). To initialize these values, set all values of C[v] to +∞ (or to any number larger than the maximum edge weight) and set each E[v] to a special flag value indicating that there is no edge connecting v to earlier vertices. let mut parent = vec![0; self.size];
let mut min_edges = (0..self.size)
.map(|i|
*self.edges.iter()
.filter(|e| (e.src == i || e.dst == i) && e.src != e.dst)
.min()
.unwrap()
).collect::<Vec<_>>();
// dbg!(&min_edges);
// helper struct for the queue let mut key = vec![f64::INFINITY; self.size];
#[derive(Clone, Debug)]
struct Vertex {
index: usize,
min_weight: f64,
}
impl Hash for Vertex { let mut mst_set = vec![false; self.size];
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.index.hash(state);
}
}
impl PartialEq for Vertex { key[0] = 0.0;
fn eq(&self, other: &Self) -> bool { parent[0] = usize::MAX;
self.min_weight == other.min_weight
}
}
impl Eq for Vertex {} for _ in 0..(self.size - 1) {
let u = {
let mut min_index = 0;
let mut min = f64::MAX;
impl PartialOrd for Vertex { for k in 0..self.size {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { if mst_set[k] == false && key[k] < min {
self.min_weight.partial_cmp(&other.min_weight) min = key[k];
} min_index = k;
} }
}
impl Ord for Vertex { min_index
fn cmp(&self, other: &Self) -> Ordering { };
self.min_weight.total_cmp(&other.min_weight)
}
}
// Initialize an empty forest F mst_set[u] = true;
let mut forest = vec![];
// and a set Q of vertices
let mut queue = BinaryHeap::<Reverse<Vertex>>::new();
// that have not yet been included in F (initially, all vertices). for v in 0..self.size {
(0..self.size) let w = self.edges[u][v];
.map(|i| Vertex { index: i, min_weight: min_edges[i].weight }) if u != v && mst_set[v] == false && w < key[v] {
.for_each(|v| queue.push(Reverse(v))); parent[v] = u;
key[v] = w;
// Repeat the following steps until Q is empty:
// Find and remove a vertex v from Q having the minimum possible value of C[v]
while let Some(Reverse(v)) = queue.pop() {
// Add v to F
forest.push(v.clone());
// Loop over the edges vw connecting v to other vertices w.
for vw in self.edges.iter()
.filter(|e| (e.src == v.index || e.dst == v.index) && e.src != e.dst) {
// the vertex in the current edge that isn't v.src
let w = if vw.src == v.index { vw.dst } else { vw.src };
// For each such edge, if w still belongs to Q and vw has smaller weight than C[w], perform the following steps:
if queue.clone().iter().any(|Reverse(e)| e.index == w || e.index == w) && vw.weight < min_edges[w].weight {
dbg!(&w);
// Set C[w] to the cost of edge vw
// Set E[w] to point to edge vw.
min_edges[w] = *vw;
} }
} }
} }
// dbg!(&min_edges); (1..self.size)
// Return F, which specifically includes the corresponding edges in E .map(|i| Edge {
forest.iter() src: parent[i],
.map(|i| min_edges[i.index]) dst: i,
// deduplication weight: self.edges[i][parent[i]],
.collect::<HashSet<_>>() })
.iter() .collect()
.map(|e| *e)
.collect::<Vec<_>>()
} }
fn find_id(belongs: &mut Vec<usize>, i: usize) -> usize { fn find_id(belongs: &mut Vec<usize>, i: usize) -> usize {
@ -194,7 +158,8 @@ impl Graph {
} }
pub fn kruskal(&self) -> Vec<Edge> { pub fn kruskal(&self) -> Vec<Edge> {
let mut edges = self.edges.iter() let edges = self.edges();
let mut edges = edges.iter()
.filter(|e| e.weight != 0.0) .filter(|e| e.weight != 0.0)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -224,7 +189,7 @@ impl Display for Graph {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for i in 0..self.size { for i in 0..self.size {
for j in 0..self.size { for j in 0..self.size {
write!(f, "{weight:.6} ", weight = self.vertex(i, j).unwrap())?; write!(f, "{weight:.6} ", weight = self.edges[i][j])?;
} }
write!(f, "\n")?; write!(f, "\n")?;
} }