39 lines
969 B
Rust
39 lines
969 B
Rust
pub type Cluster<T> = Vec<T>;
|
|
|
|
pub trait Clusterable where Self: Sized + Clone + PartialEq {
|
|
fn distance(&self, rhs: &Self) -> f64;
|
|
fn get_centroid(elements: &Vec<Self>) -> Option<Self>;
|
|
}
|
|
|
|
macro_rules! impl_clusterable {
|
|
( $type: ty) => {
|
|
impl Clusterable for $type {
|
|
fn distance(&self, rhs: &Self) -> f64 {
|
|
if self > rhs {
|
|
*self as f64 - *rhs as f64
|
|
} else {
|
|
*rhs as f64 - *self as f64
|
|
}
|
|
}
|
|
|
|
fn get_centroid(elements: &Vec<Self>) -> Option<Self> {
|
|
|
|
if elements.len() == 0 {
|
|
return None;
|
|
}
|
|
|
|
let mut tmp = 0.0 as Self;
|
|
for element in elements {
|
|
tmp += *element as Self;
|
|
}
|
|
Some(tmp / elements.len() as Self)
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl_clusterable!(f32);
|
|
impl_clusterable!(f64);
|
|
|