Adding latest

This commit is contained in:
2020-11-17 22:04:00 +00:00
parent fc088c691e
commit f836f6d8d0

View File

@@ -1,23 +1,24 @@
use std::convert::TryFrom; use std::convert::TryFrom;
use ::std::collections::HashMap;
#[derive(Debug)] #[derive(Debug)]
pub struct StatsCalculator { pub struct NewStatsCalculator<'a> {
data: &Vec<i32>, data: &'a mut Vec<i32>,
length: i32, length: u32,
total: i32, total: i32,
} }
impl StatsCalculator{ impl<'a> NewStatsCalculator<'a> {
pub fn default_data() -> Self { pub fn from_vec(initial_data: &'a mut Vec<i32>) -> Self {
Self::from_vec(&vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) let mut instance = NewStatsCalculator {
} data: initial_data,
length: 0,
pub fn from_vec(&initial_data: &Vec<i32>) -> Self { total: 0,
return StatsCalculator {
data: &initial_data,
length: Self::get_length(&initial_data),
total: Self::get_total(&initial_data),
}; };
instance.get_length();
instance.get_total();
instance
} }
// pub fn initialise(&mut self) -> () { // pub fn initialise(&mut self) -> () {
@@ -34,33 +35,44 @@ impl StatsCalculator{
// } // }
// } // }
fn get_length(&initial_data: &Vec<i32>) -> i32 { fn get_length(&mut self) {
let length = i32::try_from(initial_data.len()); let length = u32::try_from(self.data.len());
if let Ok(i) = length { if let Ok(i) = length {
return i; self.length = i;
} else { } else {
return 0; self.length = 0;
} }
} }
fn get_total(&initial_data: &Vec<i32>) -> i32 { fn get_total(&mut self) {
return initial_data.iter().sum(); self.total = self.data.iter().sum();
} }
pub fn get_mean(&self) -> f32 { pub fn get_mean(&self) -> f32 {
return self.total as f32 / self.length as f32; self.total as f32 / self.length as f32
} }
pub fn get_median(&mut self) -> f32 { pub fn get_median(&mut self) -> f32 {
let mid = self.length as usize / 2; let mid = self.length as usize / 2;
self.data.sort(); self.data.sort_unstable();
if self.length % 2 != 0 { if self.length % 2 == 0 {
return self.data[mid] as f32; (self.data[mid - 1] as f32 + self.data[mid] as f32) / 2.0
} else { } else {
return (self.data[mid - 1] as f32 + self.data[mid] as f32) / 2.0; self.data[mid] as f32
}
}
// pub fn get_mode(&self) -> HashMap<&mut i32, i32> {
// let mut mode = HashMap::new();
// for ref i in self.data {
// let count = mode.entry(i).or_insert(0);
// *count += 1;
// }
// mode
// }
} }
} }
} }