Finish course 3 week 1

This commit is contained in:
2021-02-02 14:26:50 -05:00
parent b69713fb5e
commit a13fae6ceb
6 changed files with 226 additions and 164 deletions

View File

@@ -13,14 +13,15 @@ fn child_indices(index: usize) -> (usize, usize) {
impl<T: std::cmp::PartialOrd> MinHeap<T> { impl<T: std::cmp::PartialOrd> MinHeap<T> {
fn new() -> Self { fn new() -> Self {
Self { nodes: Vec::with_capacity(128) } Self {
nodes: Vec::with_capacity(128),
}
} }
fn smaller_than_parent(&self, index: usize) -> bool { fn smaller_than_parent(&self, index: usize) -> bool {
if index == 0 { if index == 0 {
false false
} else { } else {
self.nodes[index] < self.nodes[parent_index(index)] self.nodes[index] < self.nodes[parent_index(index)]
} }
} }

View File

@@ -1,25 +1,24 @@
mod dijkstra; mod dijkstra;
mod heap; mod heap;
mod jobs;
mod merge_sort; mod merge_sort;
mod min_cut; mod min_cut;
mod prims;
mod quick_sort; mod quick_sort;
mod ssc; mod ssc;
mod util;
mod two_sum; mod two_sum;
mod jobs; mod util;
mod prims;
use std::cmp::min;
use crate::dijkstra::dijkstra; use crate::dijkstra::dijkstra;
use crate::heap::heap; use crate::heap::heap;
use crate::jobs::{jobs_1, jobs_2};
use crate::merge_sort::merge_sort_inversions; use crate::merge_sort::merge_sort_inversions;
use crate::min_cut::min_cut; use crate::min_cut::min_cut;
use crate::prims::prims;
use crate::quick_sort::quick_sort; use crate::quick_sort::quick_sort;
use crate::ssc::ssc; use crate::ssc::ssc;
use crate::two_sum::find_two_sums; use crate::two_sum::find_two_sums;
use crate::jobs::{jobs_1, jobs_2}; use std::cmp::min;
use crate::prims::prims;
#[allow(dead_code)] #[allow(dead_code)]
fn c1a2() { fn c1a2() {
@@ -91,15 +90,20 @@ fn c2a4() {
#[allow(dead_code)] #[allow(dead_code)]
fn c3a1() { fn c3a1() {
// belongs to c3a1
let mut jobs = util::read_jobs("data/c3a1_jobs.txt").unwrap(); let mut jobs = util::read_jobs("data/c3a1_jobs.txt").unwrap();
let r1 = jobs_1(&mut jobs); let r1 = jobs_1(&mut jobs);
let r2 = jobs_2(&mut jobs); let r2 = jobs_2(&mut jobs);
let g = util::read_weighted_graph("data/c3a1_edges.txt").unwrap(); let g = util::read_weighted_graph("data/c3a1_edges.txt").unwrap();
let r3 = prims(&g); let r3 = prims(&g);
println!("r1 = {}; r2 = {}; r3 = {} ", r1, r2, r3); println!("r1 = {}; r2 = {}; r3 = {} ", r1, r2, r3);
// r1 = 69119377652; r2 != 67311454237;
// r1 = 69119377652; r2 = 67311454237; r3 = -3612829
}
#[allow(dead_code)]
fn c3a2() {
println!("let's go");
} }
fn main() { fn main() {
@@ -110,5 +114,6 @@ fn main() {
// c2a2(); // c2a2();
// c2a3(); // c2a3();
// c2a4(); // c2a4();
c3a1(); // c3a1();
c3a2();
} }

View File

@@ -1,14 +1,49 @@
#[derive(Debug, Clone)] use std::collections::HashSet;
#[derive(Debug, Clone, Copy)]
pub struct Edge { pub struct Edge {
pub node_a: u32, pub weight: i32,
pub node_b: u32, pub source_id: usize,
pub weight: u32, pub target_id: usize,
} }
pub type WeightedGraph = Vec<Edge>; #[derive(Debug, Clone)]
pub struct Vertex {
pub fn prims(graph: &WeightedGraph) -> usize { pub id: usize,
println!("{:?}", graph); pub edges: Vec<Edge>,
42 }
pub type WeightedGraph = Vec<Vertex>;
pub fn prims(graph: &WeightedGraph) -> i32 {
let mut x: HashSet<usize> = HashSet::new();
let mut t = Vec::new();
x.insert(0);
while x.len() != graph.len() {
let mut min_edge = Edge {
weight: i32::MAX,
source_id: 0,
target_id: 0,
};
for node_id in &x {
for edge in &graph[*node_id].edges {
if edge.weight < min_edge.weight && !x.contains(&edge.target_id) {
min_edge = *edge;
}
}
}
x.insert(min_edge.target_id);
t.push(min_edge);
}
let mut result = 0;
for edge in &t {
result += edge.weight;
}
result
} }

View File

@@ -1,6 +1,11 @@
use std::collections::HashSet; use std::collections::HashSet;
fn binary_search<T: std::cmp::PartialOrd>(min_i: usize, max_i: usize, xs: &Vec<T>, needle: T) -> usize { fn binary_search<T: std::cmp::PartialOrd>(
min_i: usize,
max_i: usize,
xs: &Vec<T>,
needle: T,
) -> usize {
if min_i >= max_i { if min_i >= max_i {
return max_i; return max_i;
} }

View File

@@ -1,9 +1,9 @@
use crate::jobs::{Job, Jobs};
use crate::prims::{Edge, Vertex, WeightedGraph};
use std::fs::File; use std::fs::File;
use std::io; use std::io;
use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::vec::Vec; use std::vec::Vec;
use crate::jobs::{Job, Jobs};
use crate::prims::{WeightedGraph, Edge};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Graph { pub struct Graph {
@@ -163,28 +163,44 @@ pub fn read_jobs(path: &str) -> Result<Jobs, io::Error> {
} }
pub fn read_weighted_graph(path: &str) -> Result<WeightedGraph, io::Error> { pub fn read_weighted_graph(path: &str) -> Result<WeightedGraph, io::Error> {
let g = Vec::new(); let mut g = Vec::new();
let file = File::open(path)?; let file = File::open(path)?;
let br = BufReader::new(file); let br = BufReader::new(file);
let mut lines = br.lines(); let mut lines = br.lines();
let line = lines.next().unwrap().unwrap(); let line = lines.next().unwrap().unwrap();
let mut nodes = line.split_whitespace(); let mut fields = line.split_whitespace();
let n_nodes: usize = nodes.next().unwrap().parse().unwrap(); let n_nodes: usize = fields.next().unwrap().parse().unwrap();
let n_edges: usize = nodes.next().unwrap().parse().unwrap(); // let n_edges: usize = fields.next().unwrap().parse().unwrap();
println!("{:?} {:?}", n_nodes, n_edges); for i in 0..n_nodes {
// lines.next(); let node = Vertex {
// for line in lines { id: i,
// let line = line?; edges: vec![],
// let mut nodes = line.split_whitespace(); };
// let weight = nodes.next().unwrap().parse().unwrap(); g.push(node);
// let length = nodes.next().unwrap().parse().unwrap(); }
// let job = Job {
// weight: weight, for line in lines {
// length: length, let line = line?;
// }; let mut nodes = line.split_whitespace();
// jobs.push(job); let id_a: usize = nodes.next().unwrap().parse::<usize>().unwrap() - 1;
// } let id_b: usize = nodes.next().unwrap().parse::<usize>().unwrap() - 1;
let weight = nodes.next().unwrap().parse().unwrap();
let edge = Edge {
weight: weight,
source_id: id_a,
target_id: id_b,
};
g[id_a].edges.push(edge);
let edge = Edge {
weight: weight,
source_id: id_b,
target_id: id_a,
};
g[id_b].edges.push(edge);
}
Ok(g) Ok(g)
} }