44 lines
1.1 KiB
Rust
44 lines
1.1 KiB
Rust
use std::fmt::Debug;
|
|
|
|
pub trait Clusterable where Self: Sized + Clone + PartialEq + Debug {
|
|
fn distance(&self, rhs: &Self) -> f64;
|
|
fn get_centroid<'a, I>(elements: I) -> Option<Self>
|
|
where I: Iterator<Item = &'a Self>, Self: 'a;
|
|
}
|
|
|
|
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<'a, I>(elements: I) -> Option<Self>
|
|
where I: Iterator<Item = &'a Self>, Self: 'a {
|
|
|
|
let mut tmp = 0.0;
|
|
let mut count = 0.0;
|
|
for element in elements {
|
|
tmp += element;
|
|
count += 1.0;
|
|
}
|
|
|
|
if count > 0.0 {
|
|
Some(tmp / count)
|
|
} else {
|
|
None
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl_clusterable!(f32);
|
|
impl_clusterable!(f64);
|
|
|