Skip to content

Instantly share code, notes, and snippets.

@th3terrorist
Created November 15, 2021 22:07
Show Gist options
  • Save th3terrorist/685f612e012805a197c16f3aba6f03d8 to your computer and use it in GitHub Desktop.
Save th3terrorist/685f612e012805a197c16f3aba6f03d8 to your computer and use it in GitHub Desktop.
Some file structures for ads implementations
#[derive(Eq, PartialEq, Clone, Copy)]
pub struct Branch {
pub x: u32,
pub y: u32,
pub w: u32
}
impl Branch {
pub fn new(x: u32, y: u32, w: u32) -> Self {
Self {
x,
y,
w
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Node {
pub id: u32,
pub key: u32,
pub parent: i32
}
impl Node {
pub fn new(id: u32, key: u32, parent: i32) -> Self {
Self {
id,
key,
parent
}
}
}
#[derive(Clone)]
pub struct Graph {
pub verts: Vec<Node>,
pub edges: Vec<Branch>
}
#[allow(dead_code)]
impl Graph {
pub fn new(nodes: Vec<Node>) -> Self {
Self {
verts: nodes,
edges: Vec::new()
}
}
pub fn adj(&self, node: u32) -> Vec<u32> {
let mut adjv = Vec::<u32>::new();
for e in &self.edges {
if e.x == node {
adjv.push(e.y);
}
if e.y == node {
adjv.push(e.x);
}
}
return adjv;
}
pub fn adj_oriented(&self, node: u32) -> Vec<u32> {
let mut adjv = Vec::<u32>::new();
for e in &self.edges {
if e.x == node {
adjv.push(e.y);
}
}
return adjv;
}
pub fn insert(&mut self, id_n1: u32, id_n2: u32, cost: u32) {
let mut node1: Option<&Node> = None;
let mut node2: Option<&Node> = None;
for node in &self.verts {
if node.id == id_n1 {
node1 = Some(node);
}
if node.id == id_n2 {
node2 = Some(node);
}
}
if node1.is_none() || node2.is_none() {
panic!("One or more of the given ids doesn't exist");
}
self.edges.push(Branch::new(id_n1, id_n2, cost));
}
pub fn branch(&self, node1: u32, node2: u32) -> Option<&Branch> {
let lr = self.branch_oriented(node1, node2);
let rl = self.branch_oriented(node2, node1);
if lr.is_none() {
return rl
}
lr
}
pub fn branch_oriented(&self, node1: u32, node2: u32) -> Option<&Branch> {
let mut found_branch: &Branch = self.edges.first().unwrap();
for e in &self.edges {
if node1 == e.x && node2 == e.y {
found_branch = e;
}
};
return Some(found_branch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment