Last active
December 3, 2015 16:54
-
-
Save enricostano/45fc772a8a6d928925b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp::Ordering; | |
#[derive(Clone, Eq, PartialEq)] | |
struct Element { | |
weight: usize | |
} | |
impl Ord for Element { | |
fn cmp(&self, other: &Element) -> Ordering { | |
let ow = other.weight; | |
self.weight.cmp(&ow) | |
} | |
} | |
impl PartialOrd for Element { | |
fn partial_cmp(&self, other: &Element) -> Option<Ordering> { | |
Some(self.cmp(other)) | |
} | |
} | |
struct BranchPoint<Element: Ord> { | |
children: Vec<Element>, | |
weight: usize | |
} | |
fn create_tree<Element>(elements: &[Element], num_branches: usize) -> BranchPoint<Element> where Element: Clone + Ord { | |
if num_branches < 2 { | |
panic!("Number of branches should be at least 2, found: {}", num_branches); | |
} | |
let num_elements = elements.len(); | |
match num_elements { | |
0 => return BranchPoint { children: Vec::new(), weight: 0 }, | |
1 => return BranchPoint { children: Vec::from(elements), weight: elements.first().unwrap().weight }, | |
_ => return BranchPoint { children: Vec::new(), weight: 0 }, | |
} | |
} | |
#[test] | |
#[should_panic] | |
fn it_does_not_accept_num_branch_smaller_than_2() { | |
let alphabet = vec![0]; | |
let v = vec![Element { weight: 15 }]; | |
create_tree(&v, alphabet.len() as usize); | |
} | |
#[test] | |
fn when_0_elements_returns_empty_branch_point() { | |
let alphabet = vec![1, 2]; | |
let v: Vec<Element> = Vec::new(); | |
let tree = create_tree(&v, alphabet.len() as usize); | |
assert!(tree.children.is_empty()); | |
assert_eq!(tree.weight, 0); | |
} | |
#[test] | |
fn when_1_elements_returns_1_branch_point() { | |
let alphabet = vec![1, 2]; | |
let v = vec![Element { weight: 15 }]; | |
let tree = create_tree(&v, alphabet.len() as usize); | |
assert_eq!(tree.children.len(), 1); | |
assert_eq!(tree.weight, 13); | |
} | |
#[test] | |
fn trying_out_ord() { | |
let el1 = Element { weight: 15 }; | |
let el2 = Element { weight: 15 }; | |
assert_eq!(el1.cmp(&el2), Ordering::Equal); | |
} |
Author
enricostano
commented
Dec 3, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment