Adding latest
This commit is contained in:
63
src/stats.rs
Normal file
63
src/stats.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use std::convert::TryFrom;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StatsCalculator {
|
||||
data: Vec<i32>,
|
||||
}
|
||||
|
||||
impl StatsCalculator {
|
||||
pub fn default_data() -> Self {
|
||||
Self::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
|
||||
}
|
||||
|
||||
pub fn from_vec(initial_data: Vec<i32>) -> Self {
|
||||
return StatsCalculator { data: initial_data };
|
||||
}
|
||||
|
||||
// pub fn initialise(&mut self) -> () {
|
||||
// self.total = self.data.iter().sum();
|
||||
// let length = i32::try_from(self.data.len());
|
||||
// // self.length = match length {
|
||||
// // Ok(i) => i,
|
||||
// // _ => 0,
|
||||
// // };
|
||||
// if let Ok(i) = length {
|
||||
// self.length = i;
|
||||
// } else {
|
||||
// self.length = 0;
|
||||
// }
|
||||
// }
|
||||
|
||||
fn get_length(&self) -> i32 {
|
||||
let length = i32::try_from(self.data.len());
|
||||
|
||||
if let Ok(i) = length {
|
||||
return i;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_total(&self) -> i32 {
|
||||
return self.data.iter().sum();
|
||||
}
|
||||
|
||||
pub fn get_mean(&self) -> f32 {
|
||||
let total = self.get_total();
|
||||
let length = self.get_length();
|
||||
return total as f32 / length as f32;
|
||||
}
|
||||
|
||||
pub fn get_median(&mut self) -> f32 {
|
||||
let length = self.get_length();
|
||||
let mid = length as usize / 2;
|
||||
|
||||
self.data.sort();
|
||||
|
||||
if length % 2 != 0 {
|
||||
return self.data[mid] as f32;
|
||||
} else {
|
||||
return (self.data[mid - 1] as f32 + self.data[mid] as f32) / 2.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user