Skip to content

Instantly share code, notes, and snippets.

@mike239x
Last active August 28, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike239x/fcbbb99f9e39e7c76f699a4046e2ec69 to your computer and use it in GitHub Desktop.
Save mike239x/fcbbb99f9e39e7c76f699a4046e2ec69 to your computer and use it in GitHub Desktop.
Trying to create graphs in Rust
// this code is released under creative common license (CC0),
// meaning you are free to use/modify/distribute it in any way you see fit
// and I am not responsible for anything that happens
trait Graph {
type Node;
type Edge;
fn add_node(self: &mut Self, node: Self::Node);
fn add_edge(self: &mut Self, edge: Self::Edge);
fn incident_edges(self: &Self, node: Self::Node) -> Vec<Self::Edge>;
}
#[derive(Debug, Clone)]
struct Node {
id: u32,
data: u32,
}
#[derive(Debug, Clone)]
struct Edge {
from: u32,
to: u32,
id: u32,
}
use std::collections::{ HashSet, HashMap };
struct G {
nodes: HashMap<u32, Node>,
edges: HashMap<u32, Edge>,
node_to_edges: HashMap<u32, HashSet<u32>>,
}
impl G {
fn new() -> G {
G {
nodes: HashMap::<u32, Node>::new(),
edges: HashMap::<u32, Edge>::new(),
node_to_edges: HashMap::<u32, HashSet<u32>>::new(),
}
}
}
use std::fmt;
impl fmt::Debug for G {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "nodes: {:?}, edges: {:?}", self.nodes.keys(), self.edges.keys())
}
}
impl Graph for G {
type Node = Node;
type Edge = Edge;
fn add_node(self: &mut Self, node: Self::Node) {
self.nodes.insert(node.id, node.clone());
self.node_to_edges.insert(node.id, HashSet::<u32>::new());
}
fn add_edge(self: &mut Self, edge: Self::Edge) {
self.edges.insert(edge.id, edge.clone());
for n in [edge.from, edge.to].iter() {
let connected_edges = self.node_to_edges.get_mut(n);
match connected_edges {
Some(v) => { v.insert(edge.id); },
None => panic!("one of the nodes is not in the graph")
}
}
}
fn incident_edges(self: &Self, node: Self::Node) -> Vec<Self::Edge> {
match self.node_to_edges.get(&node.id) {
Some(v) => v.iter().map(|e| self.edges.get(e).unwrap().clone()).collect(),
None => vec![]
}
}
}
#[cfg(test)]
mod tests {
mod graph {
#[test]
fn has_implementation() {
#[allow(unused_imports)]
use crate::{Graph, G};
let g = G::new();
dbg!(g);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment