Files
algos/src/util.rs

69 lines
2.0 KiB
Rust

use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::vec::Vec;
#[derive(Debug, Clone)]
pub struct Graph {
pub nodes: Vec<u32>,
pub edges: Vec<(u32, u32)>,
}
pub fn read_to_vector(path: &str) -> Result<Vec<i64>, io::Error> {
let file = File::open(path)?;
let br = BufReader::new(file);
let mut v = Vec::new();
for line in br.lines() {
let line = line?;
let n = line
.trim()
.parse()
.map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
v.push(n);
}
Ok(v)
}
pub fn read_to_graph(path: &str) -> Result<Graph, io::Error> {
let mut g = Graph { nodes: vec![], edges: vec![] };
let file = File::open(path)?;
let br = BufReader::new(file);
for line in br.lines() {
let line = line?;
let mut nodes = line.split_whitespace();
let current_node = nodes.next().unwrap().parse().unwrap();
g.nodes.push(current_node);
for neightbor in nodes {
let neightbor: u32 = neightbor.parse().unwrap();
// If the neighbor is smaller than the current node that means we
// have already added it when we iterated over that smaller node.
// Hence, we do not add the edge again.
if neightbor > current_node {
let edge = (current_node, neightbor);
g.edges.push(edge);
}
}
}
Ok(g)
}
pub fn read_to_directed_graph(path: &str) -> Result<Graph, io::Error> {
let mut g = Graph { nodes: vec![], edges: vec![] };
let file = File::open(path)?;
let br = BufReader::new(file);
for line in br.lines() {
let line = line?;
let mut nodes = line.split_whitespace();
let first_node = nodes.next().unwrap().parse().unwrap();
let second_node = nodes.next().unwrap().parse().unwrap();
let edge = (first_node, second_node);
g.edges.push(edge);
}
println!("{:?}", g);
Ok(g)
}