commit fd7dc3268d1ec6a42958c9ab6330fe4d8f9a5254 Author: Daniel Tomlinson Date: Sun Nov 15 16:44:29 2020 +0000 Adding latest diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..940fcf0 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "exercises" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9d33604 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "exercises" +version = "0.1.0" +authors = ["Daniel Tomlinson "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..84a9584 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,9 @@ +mod stats; + +fn main() { + // Stats + let mut numbers = stats::StatsCalculator::default_data(); + println!("Data: {:?}", numbers); + println!("Mean: {:?}", numbers.get_mean()); + println!("Median: {:?}", numbers.get_median()); +} diff --git a/src/stats.rs b/src/stats.rs new file mode 100644 index 0000000..edb474e --- /dev/null +++ b/src/stats.rs @@ -0,0 +1,63 @@ +use std::convert::TryFrom; + +#[derive(Debug)] +pub struct StatsCalculator { + data: Vec, +} + +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) -> 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; + } + } +}